comfy-peer-host 0.1.0__tar.gz
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.
- comfy_peer_host-0.1.0/.gitignore +6 -0
- comfy_peer_host-0.1.0/PKG-INFO +119 -0
- comfy_peer_host-0.1.0/README.md +95 -0
- comfy_peer_host-0.1.0/comfy_peer_host/__init__.py +8 -0
- comfy_peer_host-0.1.0/comfy_peer_host/__main__.py +143 -0
- comfy_peer_host-0.1.0/comfy_peer_host/binarypack.py +198 -0
- comfy_peer_host-0.1.0/comfy_peer_host/comfy.py +118 -0
- comfy_peer_host-0.1.0/comfy_peer_host/host.py +375 -0
- comfy_peer_host-0.1.0/comfy_peer_host/peerjs.py +327 -0
- comfy_peer_host-0.1.0/pyproject.toml +42 -0
- comfy_peer_host-0.1.0/tests/binarypack_vectors.json +1 -0
- comfy_peer_host-0.1.0/tests/make_vectors.mjs +13 -0
- comfy_peer_host-0.1.0/tests/test_binarypack.py +33 -0
- comfy_peer_host-0.1.0/tests/test_host.py +64 -0
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: comfy-peer-host
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Headless collaboration host for Comfy UI Web: lets people build and run ComfyUI graphs on this machine over WebRTC (PeerJS), no browser needed.
|
|
5
|
+
Project-URL: Homepage, https://github.com/mastashake08/comfy-peer-host
|
|
6
|
+
Project-URL: Repository, https://github.com/mastashake08/comfy-peer-host
|
|
7
|
+
Project-URL: Issues, https://github.com/mastashake08/comfy-peer-host/issues
|
|
8
|
+
Project-URL: Web app, https://mastashake08.github.io/comfy-ui-web/
|
|
9
|
+
Keywords: collaboration,comfyui,peerjs,stable-diffusion,webrtc
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Environment :: Console
|
|
12
|
+
Classifier: Framework :: AsyncIO
|
|
13
|
+
Classifier: Intended Audience :: End Users/Desktop
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Topic :: Multimedia :: Graphics
|
|
20
|
+
Requires-Python: >=3.11
|
|
21
|
+
Requires-Dist: aiohttp>=3.9
|
|
22
|
+
Requires-Dist: aiortc>=1.9
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
# comfy-peer-host
|
|
26
|
+
|
|
27
|
+
A headless host for [Comfy UI Web](https://github.com/mastashake08/comfy-ui-web) collaboration sessions.
|
|
28
|
+
Run it on the computer that has ComfyUI, and people can join from their browser with an invite link.
|
|
29
|
+
They build the graph together and run it on this computer's ComfyUI, even when nobody has the web app open here.
|
|
30
|
+
|
|
31
|
+
It speaks the same peer-to-peer protocol as the web app's own **Collaborate** host (WebRTC over [PeerJS](https://peerjs.com)), so guests can't tell the difference:
|
|
32
|
+
|
|
33
|
+
- Guests get this server's node list and the shared graph, and their edits sync live between everyone.
|
|
34
|
+
- Anyone can press **Queue**. The prompt runs on this machine's ComfyUI, and progress, live previews, errors and result images stream back to every guest.
|
|
35
|
+
- The shared graph is saved to disk, and the session ID (so the invite link) stays the same across restarts.
|
|
36
|
+
|
|
37
|
+
## Install and run
|
|
38
|
+
|
|
39
|
+
Requires Python 3.11+.
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
pipx install comfy-peer-host # or: uv tool install comfy-peer-host
|
|
43
|
+
comfy-peer-host # ComfyUI at http://127.0.0.1:8188
|
|
44
|
+
comfy-peer-host --comfy-url http://127.0.0.1:8189 --name "Studio PC"
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Or run it once without installing: `uvx comfy-peer-host`. From a source checkout: `uv run comfy-peer-host`.
|
|
48
|
+
|
|
49
|
+
It prints the invite link:
|
|
50
|
+
|
|
51
|
+
```
|
|
52
|
+
Comfy UI Web host is running.
|
|
53
|
+
Invite link: https://mastashake08.github.io/comfy-ui-web/#join=cuw-txvwcd8gectw
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Share the link, or have people paste the code into **Collaborate → Join** in the web app.
|
|
57
|
+
|
|
58
|
+
| Option | Default | |
|
|
59
|
+
| --- | --- | --- |
|
|
60
|
+
| `--comfy-url` | `http://127.0.0.1:8188` (or `$COMFY_URL`) | ComfyUI server to run prompts on |
|
|
61
|
+
| `--name` | `Host` | Name shown to guests |
|
|
62
|
+
| `--workflow FILE` | | Start the shared graph from a workflow saved in the web app (Workflow → Save) |
|
|
63
|
+
| `--state-dir` | `~/.comfy-peer-host` | Where the session ID and shared graph (`graph.json`) are kept |
|
|
64
|
+
| `--new-id` | | Make a new session ID; old invite links stop working |
|
|
65
|
+
| `--session-id cuw-…` | | Use a specific session ID |
|
|
66
|
+
| `--app-url` | the hosted web app | Web app used in the invite link |
|
|
67
|
+
| `--turn` | off | Also offer PeerJS's public TURN relay, for guests behind very strict networks |
|
|
68
|
+
| `--peerjs-host/-port/-path/-key`, `--insecure-signalling` | PeerJS cloud | Use your own PeerJS server |
|
|
69
|
+
|
|
70
|
+
ComfyUI needs no special flags: the host talks to it from the same machine.
|
|
71
|
+
|
|
72
|
+
### Keep it running (macOS)
|
|
73
|
+
|
|
74
|
+
Save this as `~/Library/LaunchAgents/com.comfy-peer-host.plist`, adjusting the paths, then run
|
|
75
|
+
`launchctl load ~/Library/LaunchAgents/com.comfy-peer-host.plist`:
|
|
76
|
+
|
|
77
|
+
```xml
|
|
78
|
+
<?xml version="1.0" encoding="UTF-8"?>
|
|
79
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
80
|
+
<plist version="1.0"><dict>
|
|
81
|
+
<key>Label</key><string>com.comfy-peer-host</string>
|
|
82
|
+
<key>ProgramArguments</key><array>
|
|
83
|
+
<string>/path/to/comfy-peer-host</string> <!-- output of: which comfy-peer-host -->
|
|
84
|
+
<string>--name</string><string>Studio PC</string>
|
|
85
|
+
</array>
|
|
86
|
+
<key>RunAtLoad</key><true/>
|
|
87
|
+
<key>KeepAlive</key><true/>
|
|
88
|
+
<key>StandardOutPath</key><string>/tmp/comfy-peer-host.log</string>
|
|
89
|
+
<key>StandardErrorPath</key><string>/tmp/comfy-peer-host.log</string>
|
|
90
|
+
</dict></plist>
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
## Security
|
|
94
|
+
|
|
95
|
+
Anyone who has the invite link can edit the shared graph and run prompts on your GPU. Treat the link like a password.
|
|
96
|
+
Use `--new-id` to revoke it. Guests can't read your files: they only see the node list and the shared graph, and they can only queue prompts.
|
|
97
|
+
|
|
98
|
+
## How it works
|
|
99
|
+
|
|
100
|
+
- `peerjs.py`: a small PeerJS-compatible peer built on [aiortc](https://github.com/aiortc/aiortc). It registers with the PeerJS signalling server, answers guests' WebRTC offers, and uses PeerJS's "binary" data-channel format (BinaryPack, with messages over 16,300 bytes split into chunks).
|
|
101
|
+
- `binarypack.py`: a byte-for-byte port of `peerjs-js-binarypack`, tested against vectors produced by the JavaScript library.
|
|
102
|
+
- `comfy.py`: async ComfyUI HTTP and websocket client.
|
|
103
|
+
- `host.py`: the session protocol (welcome, graph ops, cursors, queueing, forwarding progress, previews and images), matching the web app's `src/lib/collab.js`.
|
|
104
|
+
|
|
105
|
+
## Development
|
|
106
|
+
|
|
107
|
+
```bash
|
|
108
|
+
uv run --group dev pytest
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
### Releasing
|
|
112
|
+
|
|
113
|
+
1. Bump `version` in `pyproject.toml` and commit.
|
|
114
|
+
2. Tag and push: `git tag v0.2.0 && git push origin v0.2.0`.
|
|
115
|
+
|
|
116
|
+
The **Release** workflow tests, checks the tag matches the version, builds the wheel and sdist, publishes them to
|
|
117
|
+
PyPI (trusted publishing, no token stored) and creates a GitHub Release with both files attached.
|
|
118
|
+
|
|
119
|
+
To regenerate the BinaryPack test vectors, run `tests/make_vectors.mjs` with Node from a `comfy-ui-web` checkout (it imports `peerjs-js-binarypack`).
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
# comfy-peer-host
|
|
2
|
+
|
|
3
|
+
A headless host for [Comfy UI Web](https://github.com/mastashake08/comfy-ui-web) collaboration sessions.
|
|
4
|
+
Run it on the computer that has ComfyUI, and people can join from their browser with an invite link.
|
|
5
|
+
They build the graph together and run it on this computer's ComfyUI, even when nobody has the web app open here.
|
|
6
|
+
|
|
7
|
+
It speaks the same peer-to-peer protocol as the web app's own **Collaborate** host (WebRTC over [PeerJS](https://peerjs.com)), so guests can't tell the difference:
|
|
8
|
+
|
|
9
|
+
- Guests get this server's node list and the shared graph, and their edits sync live between everyone.
|
|
10
|
+
- Anyone can press **Queue**. The prompt runs on this machine's ComfyUI, and progress, live previews, errors and result images stream back to every guest.
|
|
11
|
+
- The shared graph is saved to disk, and the session ID (so the invite link) stays the same across restarts.
|
|
12
|
+
|
|
13
|
+
## Install and run
|
|
14
|
+
|
|
15
|
+
Requires Python 3.11+.
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
pipx install comfy-peer-host # or: uv tool install comfy-peer-host
|
|
19
|
+
comfy-peer-host # ComfyUI at http://127.0.0.1:8188
|
|
20
|
+
comfy-peer-host --comfy-url http://127.0.0.1:8189 --name "Studio PC"
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Or run it once without installing: `uvx comfy-peer-host`. From a source checkout: `uv run comfy-peer-host`.
|
|
24
|
+
|
|
25
|
+
It prints the invite link:
|
|
26
|
+
|
|
27
|
+
```
|
|
28
|
+
Comfy UI Web host is running.
|
|
29
|
+
Invite link: https://mastashake08.github.io/comfy-ui-web/#join=cuw-txvwcd8gectw
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Share the link, or have people paste the code into **Collaborate → Join** in the web app.
|
|
33
|
+
|
|
34
|
+
| Option | Default | |
|
|
35
|
+
| --- | --- | --- |
|
|
36
|
+
| `--comfy-url` | `http://127.0.0.1:8188` (or `$COMFY_URL`) | ComfyUI server to run prompts on |
|
|
37
|
+
| `--name` | `Host` | Name shown to guests |
|
|
38
|
+
| `--workflow FILE` | | Start the shared graph from a workflow saved in the web app (Workflow → Save) |
|
|
39
|
+
| `--state-dir` | `~/.comfy-peer-host` | Where the session ID and shared graph (`graph.json`) are kept |
|
|
40
|
+
| `--new-id` | | Make a new session ID; old invite links stop working |
|
|
41
|
+
| `--session-id cuw-…` | | Use a specific session ID |
|
|
42
|
+
| `--app-url` | the hosted web app | Web app used in the invite link |
|
|
43
|
+
| `--turn` | off | Also offer PeerJS's public TURN relay, for guests behind very strict networks |
|
|
44
|
+
| `--peerjs-host/-port/-path/-key`, `--insecure-signalling` | PeerJS cloud | Use your own PeerJS server |
|
|
45
|
+
|
|
46
|
+
ComfyUI needs no special flags: the host talks to it from the same machine.
|
|
47
|
+
|
|
48
|
+
### Keep it running (macOS)
|
|
49
|
+
|
|
50
|
+
Save this as `~/Library/LaunchAgents/com.comfy-peer-host.plist`, adjusting the paths, then run
|
|
51
|
+
`launchctl load ~/Library/LaunchAgents/com.comfy-peer-host.plist`:
|
|
52
|
+
|
|
53
|
+
```xml
|
|
54
|
+
<?xml version="1.0" encoding="UTF-8"?>
|
|
55
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
56
|
+
<plist version="1.0"><dict>
|
|
57
|
+
<key>Label</key><string>com.comfy-peer-host</string>
|
|
58
|
+
<key>ProgramArguments</key><array>
|
|
59
|
+
<string>/path/to/comfy-peer-host</string> <!-- output of: which comfy-peer-host -->
|
|
60
|
+
<string>--name</string><string>Studio PC</string>
|
|
61
|
+
</array>
|
|
62
|
+
<key>RunAtLoad</key><true/>
|
|
63
|
+
<key>KeepAlive</key><true/>
|
|
64
|
+
<key>StandardOutPath</key><string>/tmp/comfy-peer-host.log</string>
|
|
65
|
+
<key>StandardErrorPath</key><string>/tmp/comfy-peer-host.log</string>
|
|
66
|
+
</dict></plist>
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Security
|
|
70
|
+
|
|
71
|
+
Anyone who has the invite link can edit the shared graph and run prompts on your GPU. Treat the link like a password.
|
|
72
|
+
Use `--new-id` to revoke it. Guests can't read your files: they only see the node list and the shared graph, and they can only queue prompts.
|
|
73
|
+
|
|
74
|
+
## How it works
|
|
75
|
+
|
|
76
|
+
- `peerjs.py`: a small PeerJS-compatible peer built on [aiortc](https://github.com/aiortc/aiortc). It registers with the PeerJS signalling server, answers guests' WebRTC offers, and uses PeerJS's "binary" data-channel format (BinaryPack, with messages over 16,300 bytes split into chunks).
|
|
77
|
+
- `binarypack.py`: a byte-for-byte port of `peerjs-js-binarypack`, tested against vectors produced by the JavaScript library.
|
|
78
|
+
- `comfy.py`: async ComfyUI HTTP and websocket client.
|
|
79
|
+
- `host.py`: the session protocol (welcome, graph ops, cursors, queueing, forwarding progress, previews and images), matching the web app's `src/lib/collab.js`.
|
|
80
|
+
|
|
81
|
+
## Development
|
|
82
|
+
|
|
83
|
+
```bash
|
|
84
|
+
uv run --group dev pytest
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
### Releasing
|
|
88
|
+
|
|
89
|
+
1. Bump `version` in `pyproject.toml` and commit.
|
|
90
|
+
2. Tag and push: `git tag v0.2.0 && git push origin v0.2.0`.
|
|
91
|
+
|
|
92
|
+
The **Release** workflow tests, checks the tag matches the version, builds the wheel and sdist, publishes them to
|
|
93
|
+
PyPI (trusted publishing, no token stored) and creates a GitHub Release with both files attached.
|
|
94
|
+
|
|
95
|
+
To regenerate the BinaryPack test vectors, run `tests/make_vectors.mjs` with Node from a `comfy-ui-web` checkout (it imports `peerjs-js-binarypack`).
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""Headless collaboration host for Comfy UI Web."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
__version__ = version("comfy-peer-host")
|
|
7
|
+
except PackageNotFoundError: # running from a source checkout without install
|
|
8
|
+
__version__ = "0.0.0"
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""comfy-peer-host: run a Comfy UI Web collaboration session from this machine, no browser needed."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import asyncio
|
|
7
|
+
import json
|
|
8
|
+
import logging
|
|
9
|
+
import os
|
|
10
|
+
import secrets
|
|
11
|
+
import signal
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from . import __version__
|
|
15
|
+
from .comfy import ComfyClient
|
|
16
|
+
from .host import Host
|
|
17
|
+
from .peerjs import DEFAULT_STUN, PEERJS_TURN, Peer
|
|
18
|
+
|
|
19
|
+
DEFAULT_APP = "https://mastashake08.github.io/comfy-ui-web/"
|
|
20
|
+
ID_CHARS = "abcdefghijkmnpqrstuvwxyz23456789"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def parse_args(argv=None) -> argparse.Namespace:
|
|
24
|
+
p = argparse.ArgumentParser(
|
|
25
|
+
prog="comfy-peer-host",
|
|
26
|
+
description="Host a Comfy UI Web collaboration session from this computer. Guests join with the invite "
|
|
27
|
+
"link, edit a shared graph, and every run executes on this machine's ComfyUI.",
|
|
28
|
+
)
|
|
29
|
+
p.add_argument("--comfy-url", default=os.environ.get("COMFY_URL", "http://127.0.0.1:8188"), help="ComfyUI server (default: %(default)s)")
|
|
30
|
+
p.add_argument("--name", default=os.environ.get("COMFY_PEER_NAME", "Host"), help="name shown to guests (default: %(default)s)")
|
|
31
|
+
p.add_argument("--session-id", help="fixed session id (cuw-…); by default one is generated once and reused")
|
|
32
|
+
p.add_argument("--new-id", action="store_true", help="generate a fresh session id (invalidates old invite links)")
|
|
33
|
+
p.add_argument("--state-dir", type=Path, default=Path(os.environ.get("COMFY_PEER_STATE", Path.home() / ".comfy-peer-host")), help="where the session id and shared graph are kept (default: %(default)s)")
|
|
34
|
+
p.add_argument("--workflow", type=Path, help="start the shared graph from a workflow saved in Comfy UI Web (Workflow → Save)")
|
|
35
|
+
p.add_argument("--app-url", default=DEFAULT_APP, help="web app used in the invite link (default: %(default)s)")
|
|
36
|
+
p.add_argument("--turn", action="store_true", help="also offer PeerJS's public TURN relay (helps behind strict NATs, slower setup)")
|
|
37
|
+
p.add_argument("--peerjs-host", default="0.peerjs.com", help="PeerJS signalling server (default: %(default)s)")
|
|
38
|
+
p.add_argument("--peerjs-port", type=int, default=443)
|
|
39
|
+
p.add_argument("--peerjs-path", default="/")
|
|
40
|
+
p.add_argument("--peerjs-key", default="peerjs")
|
|
41
|
+
p.add_argument("--insecure-signalling", action="store_true", help="use ws:// instead of wss:// for a self-hosted PeerJS server")
|
|
42
|
+
p.add_argument("-v", "--verbose", action="store_true")
|
|
43
|
+
p.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
44
|
+
return p.parse_args(argv)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def session_id(args) -> str:
|
|
48
|
+
cfg_file = args.state_dir / "config.json"
|
|
49
|
+
cfg = {}
|
|
50
|
+
try:
|
|
51
|
+
cfg = json.loads(cfg_file.read_text())
|
|
52
|
+
except (FileNotFoundError, json.JSONDecodeError):
|
|
53
|
+
pass
|
|
54
|
+
sid = args.session_id or (None if args.new_id else cfg.get("session_id"))
|
|
55
|
+
if not sid:
|
|
56
|
+
sid = "cuw-" + "".join(secrets.choice(ID_CHARS) for _ in range(12))
|
|
57
|
+
if not sid.startswith("cuw-") or not sid[4:].isalnum():
|
|
58
|
+
raise SystemExit("--session-id must look like cuw-<letters and digits>")
|
|
59
|
+
args.state_dir.mkdir(parents=True, exist_ok=True)
|
|
60
|
+
cfg["session_id"] = sid
|
|
61
|
+
cfg_file.write_text(json.dumps(cfg, indent=2))
|
|
62
|
+
return sid
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
async def run(args) -> None:
|
|
66
|
+
sid = session_id(args)
|
|
67
|
+
ice = list(DEFAULT_STUN) + ([PEERJS_TURN] if args.turn else [])
|
|
68
|
+
peer = Peer(
|
|
69
|
+
sid,
|
|
70
|
+
host=args.peerjs_host,
|
|
71
|
+
port=args.peerjs_port,
|
|
72
|
+
path=args.peerjs_path,
|
|
73
|
+
key=args.peerjs_key,
|
|
74
|
+
secure=not args.insecure_signalling,
|
|
75
|
+
ice_servers=ice,
|
|
76
|
+
)
|
|
77
|
+
async with ComfyClient(args.comfy_url) as comfy:
|
|
78
|
+
host = Host(peer, comfy, name=args.name, state_dir=args.state_dir)
|
|
79
|
+
if args.workflow:
|
|
80
|
+
host.load_workflow_file(args.workflow)
|
|
81
|
+
|
|
82
|
+
try:
|
|
83
|
+
info = await comfy.object_info()
|
|
84
|
+
logging.info("ComfyUI at %s: %d node types", args.comfy_url, len(info))
|
|
85
|
+
except Exception as e: # noqa: BLE001
|
|
86
|
+
logging.warning("ComfyUI at %s is not reachable yet (%s); guests can join once it is", args.comfy_url, e)
|
|
87
|
+
|
|
88
|
+
tasks = [
|
|
89
|
+
asyncio.create_task(peer.run(), name="peerjs"),
|
|
90
|
+
asyncio.create_task(comfy.listen(host.on_comfy_message, host.on_comfy_preview, host.on_comfy_state), name="comfy"),
|
|
91
|
+
]
|
|
92
|
+
try:
|
|
93
|
+
await peer.wait_open(30)
|
|
94
|
+
except asyncio.TimeoutError:
|
|
95
|
+
logging.warning("still waiting for the PeerJS server…")
|
|
96
|
+
link = f"{args.app_url.rstrip('/')}/#join={sid}"
|
|
97
|
+
print(
|
|
98
|
+
"\n Comfy UI Web host is running.\n"
|
|
99
|
+
f" Invite link: {link}\n"
|
|
100
|
+
f" Session code: {sid}\n"
|
|
101
|
+
f" Shared graph: {host.graph_file}\n"
|
|
102
|
+
" Anyone with the link can edit the graph and run it on this computer. Ctrl-C to stop.\n",
|
|
103
|
+
flush=True,
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
stop = asyncio.Event()
|
|
107
|
+
loop = asyncio.get_running_loop()
|
|
108
|
+
for sig in (signal.SIGINT, signal.SIGTERM):
|
|
109
|
+
try:
|
|
110
|
+
loop.add_signal_handler(sig, stop.set)
|
|
111
|
+
except NotImplementedError: # Windows
|
|
112
|
+
pass
|
|
113
|
+
done = asyncio.create_task(stop.wait())
|
|
114
|
+
finished, _ = await asyncio.wait([done, *tasks], return_when=asyncio.FIRST_COMPLETED)
|
|
115
|
+
for t in finished:
|
|
116
|
+
if t is not done and t.exception():
|
|
117
|
+
logging.error("stopped: %s", t.exception())
|
|
118
|
+
logging.info("shutting down…")
|
|
119
|
+
await host.shutdown()
|
|
120
|
+
await peer.stop()
|
|
121
|
+
for t in tasks:
|
|
122
|
+
t.cancel()
|
|
123
|
+
await asyncio.gather(*tasks, return_exceptions=True)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def main(argv=None) -> None:
|
|
127
|
+
args = parse_args(argv)
|
|
128
|
+
logging.basicConfig(
|
|
129
|
+
level=logging.DEBUG if args.verbose else logging.INFO,
|
|
130
|
+
format="%(asctime)s %(levelname)-7s %(name)s: %(message)s",
|
|
131
|
+
datefmt="%H:%M:%S",
|
|
132
|
+
)
|
|
133
|
+
if not args.verbose:
|
|
134
|
+
for noisy in ("aioice", "aiortc", "aiohttp"):
|
|
135
|
+
logging.getLogger(noisy).setLevel(logging.WARNING)
|
|
136
|
+
try:
|
|
137
|
+
asyncio.run(run(args))
|
|
138
|
+
except KeyboardInterrupt:
|
|
139
|
+
pass
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
if __name__ == "__main__":
|
|
143
|
+
main()
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"""BinaryPack: the serialization PeerJS uses for "binary" data connections.
|
|
2
|
+
|
|
3
|
+
A port of peerjs-js-binarypack (a msgpack variant). It must match the JavaScript implementation
|
|
4
|
+
byte for byte, so the type tags differ from standard msgpack:
|
|
5
|
+
0xa0+n / 0xda / 0xdb raw bytes (JS ArrayBuffer)
|
|
6
|
+
0xb0+n / 0xd8 / 0xd9 UTF-8 string
|
|
7
|
+
JavaScript has a single number type, so whole-valued floats are packed as integers, as JS does.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import math
|
|
13
|
+
import struct
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class BinaryPackError(ValueError):
|
|
18
|
+
pass
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
# ----------------------------------------------------------------------------- pack
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def pack(value: Any) -> bytes:
|
|
25
|
+
out = bytearray()
|
|
26
|
+
_pack(value, out)
|
|
27
|
+
return bytes(out)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _pack(v: Any, out: bytearray) -> None:
|
|
31
|
+
if v is None:
|
|
32
|
+
out.append(0xC0)
|
|
33
|
+
elif v is True:
|
|
34
|
+
out.append(0xC3)
|
|
35
|
+
elif v is False:
|
|
36
|
+
out.append(0xC2)
|
|
37
|
+
elif isinstance(v, str):
|
|
38
|
+
_pack_sized(v.encode("utf-8"), out, 0xB0, 0xD8, 0xD9)
|
|
39
|
+
elif isinstance(v, int):
|
|
40
|
+
_pack_int(v, out)
|
|
41
|
+
elif isinstance(v, float):
|
|
42
|
+
if math.isfinite(v) and v == math.floor(v) and abs(v) <= 2**63:
|
|
43
|
+
_pack_int(int(v), out)
|
|
44
|
+
else:
|
|
45
|
+
out.append(0xCB)
|
|
46
|
+
out += struct.pack(">d", v)
|
|
47
|
+
elif isinstance(v, (bytes, bytearray, memoryview)):
|
|
48
|
+
_pack_sized(bytes(v), out, 0xA0, 0xDA, 0xDB)
|
|
49
|
+
elif isinstance(v, (list, tuple)):
|
|
50
|
+
_pack_len(len(v), out, 0x90, 0xDC, 0xDD)
|
|
51
|
+
for item in v:
|
|
52
|
+
_pack(item, out)
|
|
53
|
+
elif isinstance(v, dict):
|
|
54
|
+
_pack_len(len(v), out, 0x80, 0xDE, 0xDF)
|
|
55
|
+
for k, item in v.items():
|
|
56
|
+
_pack(str(k) if not isinstance(k, str) else k, out)
|
|
57
|
+
_pack(item, out)
|
|
58
|
+
else:
|
|
59
|
+
raise BinaryPackError(f"Type {type(v).__name__} not supported")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _pack_len(n: int, out: bytearray, fix: int, tag16: int, tag32: int) -> None:
|
|
63
|
+
if n <= 0x0F:
|
|
64
|
+
out.append(fix + n)
|
|
65
|
+
elif n <= 0xFFFF:
|
|
66
|
+
out.append(tag16)
|
|
67
|
+
out += struct.pack(">H", n)
|
|
68
|
+
elif n <= 0xFFFFFFFF:
|
|
69
|
+
out.append(tag32)
|
|
70
|
+
out += struct.pack(">I", n)
|
|
71
|
+
else:
|
|
72
|
+
raise BinaryPackError("Invalid length")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _pack_sized(data: bytes, out: bytearray, fix: int, tag16: int, tag32: int) -> None:
|
|
76
|
+
_pack_len(len(data), out, fix, tag16, tag32)
|
|
77
|
+
out += data
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _pack_int(n: int, out: bytearray) -> None:
|
|
81
|
+
if -32 <= n <= 0x7F:
|
|
82
|
+
out.append(n & 0xFF)
|
|
83
|
+
elif 0 <= n <= 0xFF:
|
|
84
|
+
out += b"\xcc" + struct.pack(">B", n)
|
|
85
|
+
elif -128 <= n <= 0x7F:
|
|
86
|
+
out += b"\xd0" + struct.pack(">b", n)
|
|
87
|
+
elif 0 <= n <= 0xFFFF:
|
|
88
|
+
out += b"\xcd" + struct.pack(">H", n)
|
|
89
|
+
elif -32768 <= n <= 0x7FFF:
|
|
90
|
+
out += b"\xd1" + struct.pack(">h", n)
|
|
91
|
+
elif 0 <= n <= 0xFFFFFFFF:
|
|
92
|
+
out += b"\xce" + struct.pack(">I", n)
|
|
93
|
+
elif -(2**31) <= n <= 2**31 - 1:
|
|
94
|
+
out += b"\xd2" + struct.pack(">i", n)
|
|
95
|
+
elif -(2**63) <= n <= 2**63 - 1:
|
|
96
|
+
out += b"\xd3" + struct.pack(">q", n)
|
|
97
|
+
elif 0 <= n <= 2**64 - 1:
|
|
98
|
+
out += b"\xcf" + struct.pack(">Q", n)
|
|
99
|
+
else:
|
|
100
|
+
raise BinaryPackError("Invalid integer")
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
# ----------------------------------------------------------------------------- unpack
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def unpack(data: bytes) -> Any:
|
|
107
|
+
value, _ = _unpack(memoryview(data), 0)
|
|
108
|
+
return value
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _unpack(b: memoryview, i: int) -> tuple[Any, int]:
|
|
112
|
+
if i >= len(b):
|
|
113
|
+
raise BinaryPackError("read index out of range")
|
|
114
|
+
t = b[i]
|
|
115
|
+
i += 1
|
|
116
|
+
if t < 0x80:
|
|
117
|
+
return t, i
|
|
118
|
+
if (t ^ 0xE0) < 0x20:
|
|
119
|
+
return (t ^ 0xE0) - 0x20, i
|
|
120
|
+
if (t ^ 0xA0) <= 0x0F:
|
|
121
|
+
return _raw(b, i, t ^ 0xA0)
|
|
122
|
+
if (t ^ 0xB0) <= 0x0F:
|
|
123
|
+
return _str(b, i, t ^ 0xB0)
|
|
124
|
+
if (t ^ 0x90) <= 0x0F:
|
|
125
|
+
return _array(b, i, t ^ 0x90)
|
|
126
|
+
if (t ^ 0x80) <= 0x0F:
|
|
127
|
+
return _map(b, i, t ^ 0x80)
|
|
128
|
+
|
|
129
|
+
def num(fmt: str, size: int) -> tuple[Any, int]:
|
|
130
|
+
if i + size > len(b):
|
|
131
|
+
raise BinaryPackError("read index out of range")
|
|
132
|
+
return struct.unpack_from(fmt, b, i)[0], i + size
|
|
133
|
+
|
|
134
|
+
if t in (0xC0, 0xC1, 0xD4, 0xD5, 0xD6, 0xD7):
|
|
135
|
+
return None, i
|
|
136
|
+
if t == 0xC2:
|
|
137
|
+
return False, i
|
|
138
|
+
if t == 0xC3:
|
|
139
|
+
return True, i
|
|
140
|
+
if t == 0xCA:
|
|
141
|
+
return num(">f", 4)
|
|
142
|
+
if t == 0xCB:
|
|
143
|
+
return num(">d", 8)
|
|
144
|
+
if t == 0xCC:
|
|
145
|
+
return num(">B", 1)
|
|
146
|
+
if t == 0xCD:
|
|
147
|
+
return num(">H", 2)
|
|
148
|
+
if t == 0xCE:
|
|
149
|
+
return num(">I", 4)
|
|
150
|
+
if t == 0xCF:
|
|
151
|
+
return num(">Q", 8)
|
|
152
|
+
if t == 0xD0:
|
|
153
|
+
return num(">b", 1)
|
|
154
|
+
if t == 0xD1:
|
|
155
|
+
return num(">h", 2)
|
|
156
|
+
if t == 0xD2:
|
|
157
|
+
return num(">i", 4)
|
|
158
|
+
if t == 0xD3:
|
|
159
|
+
return num(">q", 8)
|
|
160
|
+
if t in (0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF):
|
|
161
|
+
size, i = num(">H", 2) if t % 2 == 0 else num(">I", 4)
|
|
162
|
+
if t in (0xD8, 0xD9):
|
|
163
|
+
return _str(b, i, size)
|
|
164
|
+
if t in (0xDA, 0xDB):
|
|
165
|
+
return _raw(b, i, size)
|
|
166
|
+
if t in (0xDC, 0xDD):
|
|
167
|
+
return _array(b, i, size)
|
|
168
|
+
return _map(b, i, size)
|
|
169
|
+
raise BinaryPackError(f"Unknown type tag 0x{t:02x}")
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _raw(b: memoryview, i: int, size: int) -> tuple[bytes, int]:
|
|
173
|
+
if i + size > len(b):
|
|
174
|
+
raise BinaryPackError("index is out of range")
|
|
175
|
+
return bytes(b[i : i + size]), i + size
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _str(b: memoryview, i: int, size: int) -> tuple[str, int]:
|
|
179
|
+
if i + size > len(b):
|
|
180
|
+
raise BinaryPackError("read index out of range")
|
|
181
|
+
return bytes(b[i : i + size]).decode("utf-8", errors="replace"), i + size
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _array(b: memoryview, i: int, size: int) -> tuple[list, int]:
|
|
185
|
+
items = []
|
|
186
|
+
for _ in range(size):
|
|
187
|
+
v, i = _unpack(b, i)
|
|
188
|
+
items.append(v)
|
|
189
|
+
return items, i
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _map(b: memoryview, i: int, size: int) -> tuple[dict, int]:
|
|
193
|
+
d = {}
|
|
194
|
+
for _ in range(size):
|
|
195
|
+
k, i = _unpack(b, i)
|
|
196
|
+
v, i = _unpack(b, i)
|
|
197
|
+
d[k] = v
|
|
198
|
+
return d, i
|