Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

0 downloads

dbbasic-object-server/object_realtime.py
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
object_realtime.py · 2.9 KB · 81 lines
1"""In-process live pub/sub for realtime push over websockets.
2
3The durable event log (``object_events``) remains the source of truth and
4the poll-based fallback. This hub is the live overlay: connected
5websocket subscribers receive record-change signals the instant a write
6happens — already filtered, by the caller, to what each subscriber is
7permitted to read.
8
9The hub is deliberately transport-only. It holds subscribers and their
10asyncio queues; it does not know about permissions. The server, which
11owns the policy engine, decides what a subscriber may receive and calls
12``deliver`` only for allowed events. Keeping the security decision in one
13place (the server) and the transport dumb (here) makes both easy to test.
14
15Single-process assumption: ``deliver`` is called on the server's event
16loop, and with one uvicorn worker every write and every socket share that
17loop, so ``put_nowait`` is safe. Across multiple workers each process has
18its own hub and clients fall back to polling the durable event log — see
19docs/asgi-realtime-direction.md.
20"""
21
22from __future__ import annotations
23
24import asyncio
25from dataclasses import dataclass, field
26from typing import Any
27
28ALL = "*"
29DEFAULT_QUEUE_MAX = 1000
30
31
32@dataclass(eq=False)
33class Subscriber:
34 """One connected websocket, its identity, and its outbound queue.
35
36 ``subject`` is the caller's permission subject, opaque to the hub —
37 the server reads it when deciding what to deliver. ``collections`` is
38 the set the client asked to follow (``"*"`` means every collection).
39 """
40
41 subject: Any
42 queue: "asyncio.Queue[dict[str, Any]]"
43 collections: set[str] = field(default_factory=set)
44
45 def wants(self, collection: str) -> bool:
46 return ALL in self.collections or collection in self.collections
47
48 def deliver(self, event: dict[str, Any]) -> bool:
49 """Enqueue one event; return False if the queue is full (dropped).
50
51 A dropped event is not fatal: the client refetches on reconnect
52 and the durable event log still holds it for polling.
53 """
54 try:
55 self.queue.put_nowait(event)
56 return True
57 except asyncio.QueueFull:
58 return False
59
60
61class RealtimeHub:
62 """A registry of live subscribers. No IO, no policy — just membership."""
63
64 def __init__(self) -> None:
65 self._subscribers: set[Subscriber] = set()
66
67 def add(self, subscriber: Subscriber) -> None:
68 self._subscribers.add(subscriber)
69
70 def remove(self, subscriber: Subscriber) -> None:
71 self._subscribers.discard(subscriber)
72
73 def count(self) -> int:
74 return len(self._subscribers)
75
76 def subscribers(self) -> list[Subscriber]:
77 return list(self._subscribers)
78
79 def wanting(self, collection: str) -> list[Subscriber]:
80 """Return subscribers following ``collection`` (or all collections)."""
81 return [s for s in self._subscribers if s.wants(collection)]