Skip to content

Realtime

Live CRUD notifications and presence are configured with RealtimeSettings, passed as Admin(realtime=...); see Realtime. Code outside the admin (a worker, an API route) announces a change with admin.publish_event(RealtimeEvent(...)).

from hyperadmin.realtime import RealtimeAction, RealtimeEvent

admin.publish_event(
    RealtimeEvent(model_name="order", pk=order.id, action=RealtimeAction.UPDATED)
)

API Reference

hyperadmin.realtime.RealtimeSettings

Bases: BaseModel

Opt-in configuration for real-time SSE / WebSocket endpoints.

Pass an instance to Admin(realtime=...) to enable real-time. Leaving the kwarg as None (the default) disables every code path in the realtime module — fully backward compatible.

Source code in src/hyperadmin/realtime/config.py
 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
class RealtimeSettings(BaseModel):
    """Opt-in configuration for real-time SSE / WebSocket endpoints.

    Pass an instance to ``Admin(realtime=...)`` to enable real-time. Leaving
    the kwarg as ``None`` (the default) disables every code path in the
    ``realtime`` module — fully backward compatible.
    """

    # ``PresenceBackend`` is a runtime-checkable Protocol: pydantic validates
    # ``presence`` with ``isinstance`` and rejects anything that lacks the methods.
    model_config = ConfigDict(arbitrary_types_allowed=True)

    heartbeat_interval: float = Field(
        default=15.0,
        gt=0,
        description=(
            "Seconds between heartbeats on both SSE (`:keepalive` comments) and "
            "WS (zero-byte ping). Default 15 s sits comfortably under the 60 s "
            "nginx `proxy_read_timeout` default."
        ),
    )
    max_connections: int | None = Field(
        default=None,
        ge=1,
        description=(
            "Optional cap on simultaneous connections per process. ``None`` "
            "(default) means unlimited; the cap exists as a circuit-breaker for "
            "deployments that want to fail-fast under unexpected load."
        ),
    )
    enable_test_endpoints: bool = Field(
        default=False,
        description=(
            "When ``True``, mounts ``/_test/realtime/*`` endpoints used by the "
            "Playwright suite to introspect the registry and simulate server-"
            "initiated drops. Must remain ``False`` in production."
        ),
    )
    presence: PresenceBackend | None = Field(
        default=None,
        description=(
            "Backend that tracks who is viewing / editing which record. ``None`` "
            "(default) resolves to the zero-config ``InMemoryPresence``; pass a "
            "``RedisPresence`` (``[redis]`` extra) for multi-worker deployments."
        ),
    )
    presence_ttl: float = Field(
        default=DEFAULT_PRESENCE_TTL,
        gt=0,
        description=(
            "Seconds a presence entry survives without a heartbeat. Only used to "
            "build the default ``InMemoryPresence``; an explicit ``presence`` "
            "backend carries its own TTL."
        ),
    )

    presence_redis_url: str | None = Field(
        default=None,
        description=(
            "Convenience selector for multi-worker deployments: when set (and no "
            "explicit ``presence`` backend is given) presence is stored in Redis at "
            "this URL via ``RedisPresence`` (``[redis]`` extra)."
        ),
    )

    pubsub: PubSubBackend | None = Field(
        default=None,
        description=(
            "Pub/sub backend that fans CRUD events out to every worker. ``None`` "
            "(default) resolves to the zero-config ``InMemoryPubSub``; pass a "
            "``RedisPubSub`` (``[redis]`` extra) for multi-worker deployments."
        ),
    )
    pubsub_redis_url: str | None = Field(
        default=None,
        description=(
            "Convenience selector for multi-worker deployments: when set (and no "
            "explicit ``pubsub`` backend is given) events travel over Redis at "
            "this URL via ``RedisPubSub`` (``[redis]`` extra)."
        ),
    )
    channel_prefix: str = Field(
        default=DEFAULT_CHANNEL_PREFIX,
        description=(
            "Prefix of every CRUD pub/sub channel (``<prefix>crud:<model>``). Set "
            "it to isolate several apps sharing one Redis."
        ),
    )
    notifications: bool = Field(
        default=True,
        description=(
            "Default for emitting CRUD events from every model's write paths. "
            "``AdminOptions.realtime_notifications`` overrides it per model."
        ),
    )

    def resolve_pubsub(self) -> PubSubBackend:
        """The configured ``pubsub`` backend, else Redis (when a URL is set), else in-memory."""
        if self.pubsub is not None:
            return self.pubsub
        if self.pubsub_redis_url is not None:
            return RedisPubSub(self.pubsub_redis_url)
        return InMemoryPubSub()

    def resolve_presence(self) -> PresenceBackend:
        """The configured ``presence`` backend, else Redis (when a URL is set), else in-memory."""
        if self.presence is not None:
            return self.presence
        if self.presence_redis_url is not None:
            return RedisPresence(self.presence_redis_url, default_ttl=self.presence_ttl)
        return InMemoryPresence(default_ttl=self.presence_ttl)

resolve_presence()

The configured presence backend, else Redis (when a URL is set), else in-memory.

Source code in src/hyperadmin/realtime/config.py
118
119
120
121
122
123
124
def resolve_presence(self) -> PresenceBackend:
    """The configured ``presence`` backend, else Redis (when a URL is set), else in-memory."""
    if self.presence is not None:
        return self.presence
    if self.presence_redis_url is not None:
        return RedisPresence(self.presence_redis_url, default_ttl=self.presence_ttl)
    return InMemoryPresence(default_ttl=self.presence_ttl)

resolve_pubsub()

The configured pubsub backend, else Redis (when a URL is set), else in-memory.

Source code in src/hyperadmin/realtime/config.py
110
111
112
113
114
115
116
def resolve_pubsub(self) -> PubSubBackend:
    """The configured ``pubsub`` backend, else Redis (when a URL is set), else in-memory."""
    if self.pubsub is not None:
        return self.pubsub
    if self.pubsub_redis_url is not None:
        return RedisPubSub(self.pubsub_redis_url)
    return InMemoryPubSub()

hyperadmin.realtime.RealtimeEvent dataclass

A CRUD change to one instance of model_name.

Source code in src/hyperadmin/realtime/events.py
 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
@dataclass(frozen=True)
class RealtimeEvent:
    """A CRUD change to one instance of ``model_name``."""

    model_name: str
    pk: PrimaryKey
    action: RealtimeAction
    html_fragment: str | None = None
    actor_id: str | None = None
    actor_name: str | None = None

    def to_dict(self) -> dict[str, str | None]:
        """JSON-safe mapping; ``pk`` is stringified, ``action`` is its value."""
        return {
            "model_name": self.model_name,
            "pk": str(self.pk),
            "action": self.action.value,
            "html_fragment": self.html_fragment,
            "actor_id": self.actor_id,
            "actor_name": self.actor_name,
        }

    def to_bytes(self) -> bytes:
        """UTF-8 JSON payload suitable for ``PubSubBackend.publish()``."""
        return json.dumps(self.to_dict(), separators=(",", ":")).encode()

    @classmethod
    def from_dict(cls, data: object) -> RealtimeEvent:
        """Rebuild an event from ``to_dict()`` output; ``ValueError`` if malformed."""
        if not isinstance(data, dict):
            msg = "RealtimeEvent payload must be a JSON object"
            raise ValueError(msg)
        model_name = data.get("model_name")
        pk = data.get("pk")
        html_fragment = data.get("html_fragment")
        actor_id = data.get("actor_id")
        actor_name = data.get("actor_name")
        if actor_id is not None and not isinstance(actor_id, str):
            msg = "RealtimeEvent 'actor_id' must be a string or null"
            raise ValueError(msg)
        if actor_name is not None and not isinstance(actor_name, str):
            msg = "RealtimeEvent 'actor_name' must be a string or null"
            raise ValueError(msg)
        if not isinstance(model_name, str) or not model_name:
            msg = "RealtimeEvent payload needs a non-empty string 'model_name'"
            raise ValueError(msg)
        if not isinstance(pk, str):
            msg = "RealtimeEvent payload needs a string 'pk'"
            raise ValueError(msg)
        if html_fragment is not None and not isinstance(html_fragment, str):
            msg = "RealtimeEvent 'html_fragment' must be a string or null"
            raise ValueError(msg)
        return cls(
            model_name=model_name,
            pk=pk,
            action=RealtimeAction(data.get("action")),
            html_fragment=html_fragment,
            actor_id=actor_id,
            actor_name=actor_name,
        )

    @classmethod
    def from_bytes(cls, data: bytes) -> RealtimeEvent:
        """Inverse of ``to_bytes()``; ``ValueError`` on invalid JSON or shape."""
        try:
            decoded = json.loads(data)
        except (UnicodeDecodeError, json.JSONDecodeError) as exc:
            msg = "RealtimeEvent payload is not valid UTF-8 JSON"
            raise ValueError(msg) from exc
        return cls.from_dict(decoded)

from_bytes(data) classmethod

Inverse of to_bytes(); ValueError on invalid JSON or shape.

Source code in src/hyperadmin/realtime/events.py
 99
100
101
102
103
104
105
106
107
@classmethod
def from_bytes(cls, data: bytes) -> RealtimeEvent:
    """Inverse of ``to_bytes()``; ``ValueError`` on invalid JSON or shape."""
    try:
        decoded = json.loads(data)
    except (UnicodeDecodeError, json.JSONDecodeError) as exc:
        msg = "RealtimeEvent payload is not valid UTF-8 JSON"
        raise ValueError(msg) from exc
    return cls.from_dict(decoded)

from_dict(data) classmethod

Rebuild an event from to_dict() output; ValueError if malformed.

Source code in src/hyperadmin/realtime/events.py
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
@classmethod
def from_dict(cls, data: object) -> RealtimeEvent:
    """Rebuild an event from ``to_dict()`` output; ``ValueError`` if malformed."""
    if not isinstance(data, dict):
        msg = "RealtimeEvent payload must be a JSON object"
        raise ValueError(msg)
    model_name = data.get("model_name")
    pk = data.get("pk")
    html_fragment = data.get("html_fragment")
    actor_id = data.get("actor_id")
    actor_name = data.get("actor_name")
    if actor_id is not None and not isinstance(actor_id, str):
        msg = "RealtimeEvent 'actor_id' must be a string or null"
        raise ValueError(msg)
    if actor_name is not None and not isinstance(actor_name, str):
        msg = "RealtimeEvent 'actor_name' must be a string or null"
        raise ValueError(msg)
    if not isinstance(model_name, str) or not model_name:
        msg = "RealtimeEvent payload needs a non-empty string 'model_name'"
        raise ValueError(msg)
    if not isinstance(pk, str):
        msg = "RealtimeEvent payload needs a string 'pk'"
        raise ValueError(msg)
    if html_fragment is not None and not isinstance(html_fragment, str):
        msg = "RealtimeEvent 'html_fragment' must be a string or null"
        raise ValueError(msg)
    return cls(
        model_name=model_name,
        pk=pk,
        action=RealtimeAction(data.get("action")),
        html_fragment=html_fragment,
        actor_id=actor_id,
        actor_name=actor_name,
    )

to_bytes()

UTF-8 JSON payload suitable for PubSubBackend.publish().

Source code in src/hyperadmin/realtime/events.py
60
61
62
def to_bytes(self) -> bytes:
    """UTF-8 JSON payload suitable for ``PubSubBackend.publish()``."""
    return json.dumps(self.to_dict(), separators=(",", ":")).encode()

to_dict()

JSON-safe mapping; pk is stringified, action is its value.

Source code in src/hyperadmin/realtime/events.py
49
50
51
52
53
54
55
56
57
58
def to_dict(self) -> dict[str, str | None]:
    """JSON-safe mapping; ``pk`` is stringified, ``action`` is its value."""
    return {
        "model_name": self.model_name,
        "pk": str(self.pk),
        "action": self.action.value,
        "html_fragment": self.html_fragment,
        "actor_id": self.actor_id,
        "actor_name": self.actor_name,
    }

hyperadmin.realtime.RealtimeAction

Bases: str, Enum

Kind of change a RealtimeEvent reports.

Source code in src/hyperadmin/realtime/events.py
30
31
32
33
34
35
class RealtimeAction(str, Enum):
    """Kind of change a ``RealtimeEvent`` reports."""

    CREATED = "created"
    UPDATED = "updated"
    DELETED = "deleted"