pondsocket 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pondsocket/types.py ADDED
@@ -0,0 +1,154 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Awaitable, Callable
4
+ from dataclasses import dataclass, field
5
+ from enum import StrEnum
6
+ from typing import TYPE_CHECKING, Any, TypeAlias
7
+
8
+ from pondsocket_common import (
9
+ ChannelReceivers,
10
+ PondAssigns,
11
+ PondPresence,
12
+ UserData,
13
+ )
14
+
15
+ if TYPE_CHECKING:
16
+ from .hooks import Hooks
17
+
18
+ DEFAULT_MAX_MESSAGE_SIZE: int = 1 * 1024 * 1024
19
+ DEFAULT_PING_INTERVAL: float = 30.0
20
+ DEFAULT_PONG_WAIT: float = 60.0
21
+ DEFAULT_WRITE_WAIT: float = 10.0
22
+ DEFAULT_SEND_TIMEOUT: float = 10.0
23
+ DEFAULT_INTERNAL_QUEUE_TIMEOUT: float = 30.0
24
+ DEFAULT_MAX_CONCURRENT_HANDLERS: int = 10
25
+ DEFAULT_SEND_CHANNEL_BUFFER: int = 256
26
+ DEFAULT_RECEIVE_CHANNEL_BUFFER: int = 256
27
+ DEFAULT_INTERNAL_QUEUE_BUFFER: int = 128
28
+ DEFAULT_DISPATCH_CONCURRENCY: int = 32
29
+
30
+
31
+ class TransportType(StrEnum):
32
+ WEBSOCKET = "websocket"
33
+ SSE = "sse"
34
+
35
+
36
+ class SystemEvents(StrEnum):
37
+ ACKNOWLEDGE = "ACKNOWLEDGE"
38
+ EXIT_ACKNOWLEDGE = "EXIT_ACKNOWLEDGE"
39
+ CONNECTION = "CONNECTION"
40
+ INTERNAL_ERROR = "INTERNAL_ERROR"
41
+ NOT_FOUND = "NOT_FOUND"
42
+ UNAUTHORIZED = "UNAUTHORIZED"
43
+
44
+
45
+ class SystemEntity(StrEnum):
46
+ GATEWAY = "GATEWAY"
47
+ CHANNEL = "CHANNEL"
48
+
49
+
50
+ class InternalActions(StrEnum):
51
+ ASSIGNS = "ASSIGNS"
52
+ USER_COMMAND = "USER_COMMAND"
53
+
54
+
55
+ class LeaveReason(StrEnum):
56
+ EXPLICIT_LEAVE = "explicit_leave"
57
+ CONNECTION_CLOSED = "connection_closed"
58
+ EVICTED = "evicted"
59
+
60
+
61
+ @dataclass(slots=True)
62
+ class Route:
63
+ params: dict[str, str] = field(default_factory=dict)
64
+ query: dict[str, list[str]] = field(default_factory=dict)
65
+ wildcard: str | None = None
66
+
67
+ def param(self, key: str) -> str:
68
+ return self.params.get(key, "")
69
+
70
+ def query_param(self, key: str) -> list[str]:
71
+ return self.query.get(key, [])
72
+
73
+
74
+ @dataclass(slots=True)
75
+ class Event:
76
+ action: str
77
+ channel_name: str
78
+ request_id: str
79
+ event: str
80
+ payload: Any = None
81
+ node_id: str = ""
82
+
83
+ def __post_init__(self) -> None:
84
+ if not self.action:
85
+ raise ValueError("Event.action must not be empty")
86
+ if not self.channel_name:
87
+ raise ValueError("Event.channel_name must not be empty")
88
+ if not self.request_id:
89
+ raise ValueError("Event.request_id must not be empty")
90
+ if not self.event:
91
+ raise ValueError("Event.event must not be empty")
92
+
93
+
94
+ @dataclass(slots=True)
95
+ class Options:
96
+ max_message_size: int = DEFAULT_MAX_MESSAGE_SIZE
97
+ ping_interval: float = DEFAULT_PING_INTERVAL
98
+ pong_wait: float = DEFAULT_PONG_WAIT
99
+ write_wait: float = DEFAULT_WRITE_WAIT
100
+ send_timeout: float = DEFAULT_SEND_TIMEOUT
101
+ internal_queue_timeout: float = DEFAULT_INTERNAL_QUEUE_TIMEOUT
102
+ internal_queue_buffer: int = DEFAULT_INTERNAL_QUEUE_BUFFER
103
+ dispatch_concurrency: int = DEFAULT_DISPATCH_CONCURRENCY
104
+ send_channel_buffer: int = DEFAULT_SEND_CHANNEL_BUFFER
105
+ receive_channel_buffer: int = DEFAULT_RECEIVE_CHANNEL_BUFFER
106
+ max_concurrent_handlers: int = DEFAULT_MAX_CONCURRENT_HANDLERS
107
+ max_connections: int = 0
108
+ node_id: str = ""
109
+ hooks: Hooks | None = None
110
+
111
+
112
+ Recipients: TypeAlias = ChannelReceivers
113
+
114
+
115
+ @dataclass(frozen=True, slots=True)
116
+ class AllUsers:
117
+ pass
118
+
119
+
120
+ @dataclass(frozen=True, slots=True)
121
+ class AllExceptSender:
122
+ sender_id: str
123
+
124
+
125
+ @dataclass(frozen=True, slots=True)
126
+ class ToUsers:
127
+ user_ids: tuple[str, ...]
128
+
129
+
130
+ RecipientSpec: TypeAlias = AllUsers | AllExceptSender | ToUsers
131
+
132
+
133
+ @dataclass(slots=True)
134
+ class User:
135
+ id: str
136
+ assigns: PondAssigns = field(default_factory=dict)
137
+ presence: PondPresence | None = None
138
+
139
+ def to_user_data(self) -> UserData:
140
+ return UserData(
141
+ id=self.id,
142
+ assigns=dict(self.assigns),
143
+ presence=dict(self.presence) if isinstance(self.presence, dict) else {},
144
+ )
145
+
146
+
147
+ @dataclass(slots=True)
148
+ class MessageEvent:
149
+ event: Event
150
+ user: User
151
+
152
+
153
+ HandlerFn: TypeAlias = Callable[..., Awaitable[None]]
154
+ MiddlewareFn: TypeAlias = Callable[[Any, Callable[[], Awaitable[None]]], Awaitable[None]]
pondsocket/wire.py ADDED
@@ -0,0 +1,87 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from typing import Any
5
+
6
+ from pondsocket_common import ValidationError, parse_client_message
7
+
8
+ from .types import Event
9
+
10
+
11
+ def event_to_wire(event: Event) -> dict[str, Any]:
12
+ return {
13
+ "action": event.action,
14
+ "event": event.event,
15
+ "channelName": event.channel_name,
16
+ "requestId": event.request_id,
17
+ "payload": event.payload if event.payload is not None else {},
18
+ }
19
+
20
+
21
+ def event_to_json(event: Event) -> str:
22
+ return json.dumps(event_to_wire(event), ensure_ascii=False, separators=(",", ":"))
23
+
24
+
25
+ def wire_to_event(data: dict[str, Any]) -> Event:
26
+ msg = parse_client_message(data)
27
+ return Event(
28
+ action=msg.action.value,
29
+ channel_name=msg.channel_name,
30
+ request_id=msg.request_id,
31
+ event=msg.event,
32
+ payload=msg.payload,
33
+ )
34
+
35
+
36
+ def parse_inbound_text(text: str) -> Event:
37
+ try:
38
+ data = json.loads(text)
39
+ except json.JSONDecodeError as e:
40
+ raise ValidationError(f"Invalid JSON: {e.msg}", "wireMessage") from e
41
+ if not isinstance(data, dict):
42
+ raise ValidationError("Expected object", "wireMessage")
43
+ return wire_to_event(data)
44
+
45
+
46
+ def event_to_pubsub_bytes(event: Event) -> bytes:
47
+ data: dict[str, Any] = {
48
+ "action": event.action,
49
+ "event": event.event,
50
+ "channelName": event.channel_name,
51
+ "requestId": event.request_id,
52
+ "payload": event.payload if event.payload is not None else {},
53
+ "nodeId": event.node_id,
54
+ }
55
+ return json.dumps(data, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
56
+
57
+
58
+ def pubsub_bytes_to_event(data: bytes) -> Event | None:
59
+ try:
60
+ text = data.decode("utf-8")
61
+ wire = json.loads(text)
62
+ except (UnicodeDecodeError, json.JSONDecodeError):
63
+ return None
64
+ if not isinstance(wire, dict):
65
+ return None
66
+ action = wire.get("action")
67
+ channel_name = wire.get("channelName")
68
+ request_id = wire.get("requestId")
69
+ event_name = wire.get("event")
70
+ if not isinstance(action, str) or not action:
71
+ return None
72
+ if not isinstance(channel_name, str) or not channel_name:
73
+ return None
74
+ if not isinstance(request_id, str) or not request_id:
75
+ return None
76
+ if not isinstance(event_name, str) or not event_name:
77
+ return None
78
+ payload_raw = wire.get("payload")
79
+ payload: Any = payload_raw if payload_raw is not None else {}
80
+ return Event(
81
+ action=action,
82
+ channel_name=channel_name,
83
+ request_id=request_id,
84
+ event=event_name,
85
+ payload=payload,
86
+ node_id=str(wire.get("nodeId", "")),
87
+ )
@@ -0,0 +1,144 @@
1
+ Metadata-Version: 2.4
2
+ Name: pondsocket
3
+ Version: 0.0.1
4
+ Summary: PondSocket - channel-based real-time framework with bring-your-own-server design.
5
+ Author: eleven-am
6
+ License: GPL-3.0-or-later
7
+ Requires-Python: >=3.11
8
+ Requires-Dist: pondsocket-common<0.1.0,>=0.0.1
9
+ Provides-Extra: redis
10
+ Requires-Dist: redis>=5; extra == 'redis'
11
+ Description-Content-Type: text/markdown
12
+
13
+ # pondsocket
14
+
15
+ PondSocket - channel-based real-time framework for Python. Bring-your-own-server design: the core knows nothing about HTTP frameworks or WebSocket libraries. You build the layered API (Server -> Endpoint -> Channel -> User), and an adapter (e.g. [`pondsocket-asgi`](../pondsocket-asgi/)) bridges it to your HTTP stack.
16
+
17
+ ## Install
18
+
19
+ ```
20
+ pip install pondsocket
21
+ pip install "pondsocket[redis]" # multi-node deployments
22
+ ```
23
+
24
+ ## Concepts
25
+
26
+ ```
27
+ PondSocket top-level facade, holds endpoints
28
+ └── Endpoint one URL path, runs the connection auth handler, owns transports
29
+ └── Lobby one channel pattern (e.g. "/chat/:room_id"), holds shared middleware
30
+ └── Channel one live channel instance, holds users + presence
31
+ ```
32
+
33
+ ### Five contexts, scoped to lifecycle moments
34
+
35
+ | Context | When | What it decides / does |
36
+ |---|---|---|
37
+ | `ConnectionContext` | HTTP upgrade | accept / decline socket, set initial assigns |
38
+ | `JoinContext` | per channel join | accept / decline membership, track presence |
39
+ | `EventContext` | per incoming event | broadcast, reply, update presence/assigns, evict |
40
+ | `OutgoingContext` | per recipient, per send | transform payload or block delivery |
41
+ | `LeaveContext` | user gone | final cleanup (user already removed) |
42
+
43
+ ## Minimal example
44
+
45
+ ```python
46
+ from pondsocket import ConnectionContext, EventContext, JoinContext, PondSocket
47
+
48
+
49
+ async def auth(ctx: ConnectionContext) -> None:
50
+ if ctx.query.get("token") != "secret":
51
+ ctx.decline(401, "Invalid token")
52
+ return
53
+ ctx.accept(user_id=ctx.query.get("uid", "anon"))
54
+
55
+
56
+ async def on_join(ctx: JoinContext) -> None:
57
+ await ctx.accept()
58
+ await ctx.track({"status": "online"})
59
+
60
+
61
+ async def on_message(ctx: EventContext) -> None:
62
+ await ctx.broadcast(ctx.event_name, ctx.get_payload())
63
+
64
+
65
+ pond = PondSocket()
66
+ endpoint = pond.create_endpoint("/api/socket", auth)
67
+ lobby = endpoint.create_channel("/chat/:room_id", on_join)
68
+ lobby.on_message("message", on_message)
69
+ ```
70
+
71
+ To actually serve traffic, wrap `pond` in an adapter — see [`pondsocket-asgi`](../pondsocket-asgi/) for the canonical one.
72
+
73
+ ## Distributed (multi-node)
74
+
75
+ ```python
76
+ from redis.asyncio import Redis
77
+ from pondsocket import PondSocket
78
+ from pondsocket.distributed import RedisPubSub
79
+
80
+ redis = Redis(host="localhost", port=6379)
81
+ pubsub = RedisPubSub(redis, owns_client=True)
82
+ pond = PondSocket(pubsub=pubsub)
83
+ ```
84
+
85
+ Cross-node broadcasts and presence events propagate via Redis PSUBSCRIBE. `node_id` is auto-generated when a pubsub is configured. Each broadcast carries the `nodeId` so emitters filter their own echo.
86
+
87
+ See [`pondsocket.distributed.RedisPubSub`](src/pondsocket/distributed/redis_pubsub.py) for the implementation. The `PubSub` protocol is implementable for other backends.
88
+
89
+ ## Hooks & metrics
90
+
91
+ ```python
92
+ from pondsocket import Hooks, NoopMetrics, Options, PondSocket, TokenBucketRateLimiter
93
+
94
+ hooks = Hooks(
95
+ rate_limiter=TokenBucketRateLimiter(rate=10, capacity=20),
96
+ metrics=NoopMetrics(),
97
+ )
98
+ pond = PondSocket(options=Options(hooks=hooks))
99
+ ```
100
+
101
+ Auto-fired by the framework: `connection_opened`/`connection_closed`, `channel_created`/`channel_destroyed`/`channel_joined`/`channel_left`, plus `on_connect`/`on_disconnect`/`before_join`/`after_join`/`before_message`/`after_message`.
102
+
103
+ Opt-in middleware factories for per-handler instrumentation:
104
+
105
+ ```python
106
+ from pondsocket import with_metrics, with_rate_limiter
107
+
108
+ lobby.on_message(
109
+ "message",
110
+ on_message,
111
+ with_rate_limiter(hooks, key_fn=lambda msg: msg.user.id),
112
+ with_metrics(hooks),
113
+ )
114
+ ```
115
+
116
+ ## Testing
117
+
118
+ `InMemoryTransport` is a public test utility that satisfies the `Transport` protocol without any network I/O:
119
+
120
+ ```python
121
+ from pondsocket import InMemoryTransport
122
+
123
+ t = InMemoryTransport("alice")
124
+ await endpoint.register_transport(t)
125
+
126
+ await t.push_inbound(some_event)
127
+ sent = await t.receive_sent()
128
+ ```
129
+
130
+ ## Public API
131
+
132
+ `from pondsocket import ...`
133
+
134
+ - Core: `PondSocket`, `Endpoint`, `Lobby`, `Channel`, `Options`, `Event`, `User`, `MessageEvent`, `RecipientSpec`
135
+ - Contexts: `ConnectionContext`, `JoinContext`, `EventContext`, `LeaveContext`, `OutgoingContext`
136
+ - Transport: `Transport` (Protocol), `InMemoryTransport`, `SSEServerTransport`, `TransportType`, `OnCloseCallback`, `OnMessageHandler`
137
+ - PubSub: `PubSub` (Protocol), `LocalPubSub`, `format_topic`, `match_topic`, `PubSubClosedError`
138
+ - Hooks: `Hooks`, `RateLimiter`, `MetricsCollector`, `NoopMetrics`, `TokenBucketRateLimiter`, `with_rate_limiter`, `with_metrics`
139
+ - Wire: `event_to_json`, `event_to_wire`, `parse_inbound_text`, `wire_to_event`, `event_to_pubsub_bytes`, `pubsub_bytes_to_event`
140
+ - Errors: `PondError`, status constructors, `error_event`
141
+
142
+ ## License
143
+
144
+ GPL-3.0-or-later.
@@ -0,0 +1,30 @@
1
+ pondsocket/__init__.py,sha256=6ozzo7xMW2VILFhrCMgYw7JyySpgMRIMsqWiO7kyaQs,4157
2
+ pondsocket/channel.py,sha256=fTC41AmvH90i6nEpMjehQYyjSmeENVZE-1VnYIEc_ps,19371
3
+ pondsocket/endpoint.py,sha256=I1164_rYBuAjEeW87-pwJ2BmBSjbRc05mjduQkrxoQs,12185
4
+ pondsocket/errors.py,sha256=cD4ceDU5Ot4fPK8I3y0ktA5PDq8u7z6bAdZdbrPxe6A,2100
5
+ pondsocket/hooks.py,sha256=RLFSAP6bm-hz9TWjvD9GDjwd8bYSBhTbInZmjYK0fZ4,6885
6
+ pondsocket/in_memory_transport.py,sha256=LPbktfpKfq28w9DzO6g7ytra7YJlktlltyWjvp_f37Q,3525
7
+ pondsocket/lobby.py,sha256=dAhS-N_2UvRYGlQxY0qVHLzbPF-XOEZ-Fvdn1p28J24,5643
8
+ pondsocket/middleware.py,sha256=OBDEv4ucI5w7CR2q1rPkUsE_8VnO117raF5pDoqSZXE,2796
9
+ pondsocket/parser.py,sha256=kfYEmMveCvx7O7OVx9S5nASK7J4FVXR26AwT1KdB9lA,2551
10
+ pondsocket/presence.py,sha256=S5-C3jpYzcHE1yRp6B6o8BOt_N0C--aQSyhxZzrQ3tA,3648
11
+ pondsocket/pubsub.py,sha256=tX_IL9ZDwJ6Yv4v6wFWtvdTGWUVsR4O-HYUSi27ADW0,1296
12
+ pondsocket/pubsub_local.py,sha256=MOYBfeqaQfvmsXA_qoVF-P7yEpZHIHqUuPeBEcqmybs,2793
13
+ pondsocket/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
14
+ pondsocket/server.py,sha256=nMzXmo2ln9e90EpM_bjJgvQXsoHeJXiVpG6HKg7oZcc,2376
15
+ pondsocket/sse_transport.py,sha256=HrVz_V_DoYlxgTEbdlZJQj87Jx96REB3Z3eqsq77Ky4,3530
16
+ pondsocket/store.py,sha256=kCijQCS04f76CEjwAmvscNQkF51vvUrGyLsqI3_HbsY,2449
17
+ pondsocket/transport.py,sha256=TCIXmQsbXDYXvK-NsGtLfiLE1SvHBsYN7Mxo_LvagLY,1064
18
+ pondsocket/types.py,sha256=d-jfk6Z_L16uDZy1ienDvm-yzyKuV16b5NobfLDI2-k,4004
19
+ pondsocket/wire.py,sha256=cXtbMSI4fmM8xErIOKkIjt_l0A55Qp_oaLhr4q37Y5s,2646
20
+ pondsocket/contexts/__init__.py,sha256=NOS4c6JVF-dN4s0SEDqtlIzjYrKvOwK21Qq_GFJ_D-g,418
21
+ pondsocket/contexts/connection_context.py,sha256=NQa2Lz7bsJwZDU7pJXgBRNBn4yToVdwb279HcPIYri8,3864
22
+ pondsocket/contexts/event_context.py,sha256=BRdmYKCnjNkDXX_0cERKzIAycoxuZLHvIlzjQfc9XCY,3711
23
+ pondsocket/contexts/join_context.py,sha256=jUyjTwNv0V6IMHcuIXcj-ClLOuYIlKvvPDmAtEMNEgE,5251
24
+ pondsocket/contexts/leave_context.py,sha256=AhROLc6sPbJz8G1kEYdmHD1SsHOFeGlWtBn45aYpeQY,2165
25
+ pondsocket/contexts/outgoing_context.py,sha256=hsNWucXFdEwRLQCL_l4Q85s24LhYXxQ7KpNDwkXGLYg,1661
26
+ pondsocket/distributed/__init__.py,sha256=VFkNLNSy3wyJVGx6hBDwtI6DaTulTo8LHftfvrsHM98,101
27
+ pondsocket/distributed/redis_pubsub.py,sha256=7aJi3n1U-EVFVvPOc0G2I3dFNpMuWxkA9cjA3Sb4HEo,4537
28
+ pondsocket-0.0.1.dist-info/METADATA,sha256=SRv3nUni1RTg24kEO0u5wPEwO8PcMMsd5ydEnCGykbI,5095
29
+ pondsocket-0.0.1.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
30
+ pondsocket-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any