| 1 |
#!/usr/bin/env python |
| 2 |
|
| 3 |
import asyncio |
| 4 |
import functools |
| 5 |
import os |
| 6 |
import sys |
| 7 |
import time |
| 8 |
|
| 9 |
from websockets.asyncio.server import broadcast, serve |
| 10 |
from websockets.exceptions import ConnectionClosed |
| 11 |
|
| 12 |
|
| 13 |
CLIENTS = set() |
| 14 |
|
| 15 |
|
| 16 |
async def send(websocket, message): |
| 17 |
try: |
| 18 |
await websocket.send(message) |
| 19 |
except ConnectionClosed: |
| 20 |
pass |
| 21 |
|
| 22 |
|
| 23 |
async def relay(queue, websocket): |
| 24 |
while True: |
| 25 |
message = await queue.get() |
| 26 |
await websocket.send(message) |
| 27 |
|
| 28 |
|
| 29 |
class PubSub: |
| 30 |
def __init__(self): |
| 31 |
self.waiter = asyncio.get_running_loop().create_future() |
| 32 |
|
| 33 |
def publish(self, value): |
| 34 |
waiter = self.waiter |
| 35 |
self.waiter = asyncio.get_running_loop().create_future() |
| 36 |
waiter.set_result((value, self.waiter)) |
| 37 |
|
| 38 |
async def subscribe(self): |
| 39 |
waiter = self.waiter |
| 40 |
while True: |
| 41 |
value, waiter = await waiter |
| 42 |
yield value |
| 43 |
|
| 44 |
__aiter__ = subscribe |
| 45 |
|
| 46 |
|
| 47 |
async def handler(websocket, method=None): |
| 48 |
if method in ["default", "naive", "task", "wait"]: |
| 49 |
CLIENTS.add(websocket) |
| 50 |
try: |
| 51 |
await websocket.wait_closed() |
| 52 |
finally: |
| 53 |
CLIENTS.remove(websocket) |
| 54 |
elif method == "queue": |
| 55 |
queue = asyncio.Queue() |
| 56 |
relay_task = asyncio.create_task(relay(queue, websocket)) |
| 57 |
CLIENTS.add(queue) |
| 58 |
try: |
| 59 |
await websocket.wait_closed() |
| 60 |
finally: |
| 61 |
CLIENTS.remove(queue) |
| 62 |
relay_task.cancel() |
| 63 |
elif method == "pubsub": |
| 64 |
global PUBSUB |
| 65 |
async for message in PUBSUB: |
| 66 |
await websocket.send(message) |
| 67 |
else: |
| 68 |
raise NotImplementedError(f"unsupported method: {method}") |
| 69 |
|
| 70 |
|
| 71 |
async def broadcast_messages(method, size, delay): |
| 72 |
"""Broadcast messages at regular intervals.""" |
| 73 |
if method == "pubsub": |
| 74 |
global PUBSUB |
| 75 |
PUBSUB = PubSub() |
| 76 |
load_average = 0 |
| 77 |
time_average = 0 |
| 78 |
pc1, pt1 = time.perf_counter_ns(), time.process_time_ns() |
| 79 |
await asyncio.sleep(delay) |
| 80 |
while True: |
| 81 |
print(f"clients = {len(CLIENTS)}") |
| 82 |
pc0, pt0 = time.perf_counter_ns(), time.process_time_ns() |
| 83 |
load_average = 0.9 * load_average + 0.1 * (pt0 - pt1) / (pc0 - pc1) |
| 84 |
print( |
| 85 |
f"load = {(pt0 - pt1) / (pc0 - pc1) * 100:.1f}% / " |
| 86 |
f"average = {load_average * 100:.1f}%, " |
| 87 |
f"late = {(pc0 - pc1 - delay * 1e9) / 1e6:.1f} ms" |
| 88 |
) |
| 89 |
pc1, pt1 = pc0, pt0 |
| 90 |
|
| 91 |
assert size > 20 |
| 92 |
message = str(time.time_ns()).encode() + b" " + os.urandom(size - 20) |
| 93 |
|
| 94 |
if method == "default": |
| 95 |
broadcast(CLIENTS, message) |
| 96 |
elif method == "naive": |
| 97 |
# Since the loop can yield control, make a copy of CLIENTS |
| 98 |
# to avoid: RuntimeError: Set changed size during iteration |
| 99 |
for websocket in CLIENTS.copy(): |
| 100 |
await send(websocket, message) |
| 101 |
elif method == "task": |
| 102 |
for websocket in CLIENTS: |
| 103 |
asyncio.create_task(send(websocket, message)) |
| 104 |
elif method == "wait": |
| 105 |
if CLIENTS: # asyncio.wait doesn't accept an empty list |
| 106 |
await asyncio.wait( |
| 107 |
[ |
| 108 |
asyncio.create_task(send(websocket, message)) |
| 109 |
for websocket in CLIENTS |
| 110 |
] |
| 111 |
) |
| 112 |
elif method == "queue": |
| 113 |
for queue in CLIENTS: |
| 114 |
queue.put_nowait(message) |
| 115 |
elif method == "pubsub": |
| 116 |
PUBSUB.publish(message) |
| 117 |
else: |
| 118 |
raise NotImplementedError(f"unsupported method: {method}") |
| 119 |
|
| 120 |
pc2 = time.perf_counter_ns() |
| 121 |
wait = delay + (pc1 - pc2) / 1e9 |
| 122 |
time_average = 0.9 * time_average + 0.1 * (pc2 - pc1) |
| 123 |
print( |
| 124 |
f"broadcast = {(pc2 - pc1) / 1e6:.1f}ms / " |
| 125 |
f"average = {time_average / 1e6:.1f}ms, " |
| 126 |
f"wait = {wait * 1e3:.1f}ms" |
| 127 |
) |
| 128 |
await asyncio.sleep(wait) |
| 129 |
print() |
| 130 |
|
| 131 |
|
| 132 |
async def main(method, size, delay): |
| 133 |
async with serve( |
| 134 |
functools.partial(handler, method=method), |
| 135 |
"localhost", |
| 136 |
8765, |
| 137 |
compression=None, |
| 138 |
ping_timeout=None, |
| 139 |
): |
| 140 |
await broadcast_messages(method, size, delay) |
| 141 |
|
| 142 |
|
| 143 |
if __name__ == "__main__": |
| 144 |
try: |
| 145 |
method = sys.argv[1] |
| 146 |
assert method in ["default", "naive", "task", "wait", "queue", "pubsub"] |
| 147 |
size = int(sys.argv[2]) |
| 148 |
delay = float(sys.argv[3]) |
| 149 |
except Exception as exc: |
| 150 |
print(f"Usage: {sys.argv[0]} method size delay") |
| 151 |
print(" Start a server broadcasting messages with <method> e.g. naive") |
| 152 |
print(" Send a payload of <size> bytes every <delay> seconds") |
| 153 |
print() |
| 154 |
print(exc) |
| 155 |
else: |
| 156 |
asyncio.run(main(method, size, delay)) |