| 1 |
import inspect |
| 2 |
import random |
| 3 |
import string |
| 4 |
import types |
| 5 |
|
| 6 |
try: |
| 7 |
import ujson as json |
| 8 |
except ImportError: |
| 9 |
try: |
| 10 |
import simplejson as json |
| 11 |
except ImportError: |
| 12 |
import json |
| 13 |
|
| 14 |
from .._compat import range_type, string_types |
| 15 |
from ..exceptions import WebSocketError |
| 16 |
from .base import BaseProtocol |
| 17 |
|
| 18 |
|
| 19 |
def export_rpc(arg=None): |
| 20 |
if isinstance(arg, types.FunctionType): |
| 21 |
arg._rpc = arg.__name__ |
| 22 |
return arg |
| 23 |
|
| 24 |
|
| 25 |
def serialize(data): |
| 26 |
return json.dumps(data) |
| 27 |
|
| 28 |
|
| 29 |
class Prefixes(object): |
| 30 |
def __init__(self): |
| 31 |
self.prefixes = {} |
| 32 |
|
| 33 |
def add(self, prefix, uri): |
| 34 |
self.prefixes[prefix] = uri |
| 35 |
|
| 36 |
def resolve(self, curie_or_uri): |
| 37 |
if "http://" in curie_or_uri: |
| 38 |
return curie_or_uri |
| 39 |
elif ':' in curie_or_uri: |
| 40 |
prefix, proc = curie_or_uri.split(':', 1) |
| 41 |
return self.prefixes[prefix] + proc |
| 42 |
else: |
| 43 |
raise Exception(curie_or_uri) |
| 44 |
|
| 45 |
|
| 46 |
class RemoteProcedures(object): |
| 47 |
def __init__(self): |
| 48 |
self.calls = {} |
| 49 |
|
| 50 |
def register_procedure(self, uri, proc): |
| 51 |
self.calls[uri] = proc |
| 52 |
|
| 53 |
def register_object(self, uri, obj): |
| 54 |
for k in inspect.getmembers(obj, inspect.ismethod): |
| 55 |
if '_rpc' in k[1].__dict__: |
| 56 |
proc_uri = uri + k[1]._rpc |
| 57 |
self.calls[proc_uri] = (obj, k[1]) |
| 58 |
|
| 59 |
def call(self, uri, args): |
| 60 |
if uri in self.calls: |
| 61 |
proc = self.calls[uri] |
| 62 |
|
| 63 |
|
| 64 |
if isinstance(proc, tuple): |
| 65 |
if proc[1].__self__ is None: |
| 66 |
|
| 67 |
return proc[1](proc[0](), *args) |
| 68 |
else: |
| 69 |
|
| 70 |
return proc[1](*args) |
| 71 |
else: |
| 72 |
return self.calls[uri](*args) |
| 73 |
else: |
| 74 |
raise Exception("no such uri '{}'".format(uri)) |
| 75 |
|
| 76 |
|
| 77 |
class Channels(object): |
| 78 |
def __init__(self): |
| 79 |
self.channels = {} |
| 80 |
|
| 81 |
def create(self, uri, prefix_matching=False): |
| 82 |
if uri not in self.channels: |
| 83 |
self.channels[uri] = [] |
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
def subscribe(self, uri, client): |
| 88 |
if uri in self.channels: |
| 89 |
self.channels[uri].append(client) |
| 90 |
|
| 91 |
def unsubscribe(self, uri, client): |
| 92 |
if uri not in self.channels: |
| 93 |
return |
| 94 |
|
| 95 |
client_index = self.channels[uri].index(client) |
| 96 |
self.channels[uri].pop(client_index) |
| 97 |
|
| 98 |
if len(self.channels[uri]) == 0: |
| 99 |
del self.channels[uri] |
| 100 |
|
| 101 |
def publish(self, uri, event, exclude=None, eligible=None): |
| 102 |
if uri not in self.channels: |
| 103 |
return |
| 104 |
|
| 105 |
|
| 106 |
|
| 107 |
msg = [WampProtocol.MSG_EVENT, uri, event] |
| 108 |
|
| 109 |
for client in self.channels[uri]: |
| 110 |
try: |
| 111 |
client.ws.send(serialize(msg)) |
| 112 |
except WebSocketError: |
| 113 |
|
| 114 |
self.channels[uri].remove(client) |
| 115 |
|
| 116 |
|
| 117 |
class WampProtocol(BaseProtocol): |
| 118 |
MSG_WELCOME = 0 |
| 119 |
MSG_PREFIX = 1 |
| 120 |
MSG_CALL = 2 |
| 121 |
MSG_CALL_RESULT = 3 |
| 122 |
MSG_CALL_ERROR = 4 |
| 123 |
MSG_SUBSCRIBE = 5 |
| 124 |
MSG_UNSUBSCRIBE = 6 |
| 125 |
MSG_PUBLISH = 7 |
| 126 |
MSG_EVENT = 8 |
| 127 |
|
| 128 |
PROTOCOL_NAME = "wamp" |
| 129 |
|
| 130 |
def __init__(self, *args, **kwargs): |
| 131 |
self.procedures = RemoteProcedures() |
| 132 |
self.prefixes = Prefixes() |
| 133 |
self.session_id = ''.join( |
| 134 |
[random.choice(string.digits + string.letters) |
| 135 |
for i in range_type(16)]) |
| 136 |
|
| 137 |
super(WampProtocol, self).__init__(*args, **kwargs) |
| 138 |
|
| 139 |
def register_procedure(self, *args, **kwargs): |
| 140 |
self.procedures.register_procedure(*args, **kwargs) |
| 141 |
|
| 142 |
def register_object(self, *args, **kwargs): |
| 143 |
self.procedures.register_object(*args, **kwargs) |
| 144 |
|
| 145 |
def register_pubsub(self, *args, **kwargs): |
| 146 |
if not hasattr(self.server, 'channels'): |
| 147 |
self.server.channels = Channels() |
| 148 |
|
| 149 |
self.server.channels.create(*args, **kwargs) |
| 150 |
|
| 151 |
def do_handshake(self): |
| 152 |
from geventwebsocket import get_version |
| 153 |
|
| 154 |
welcome = [ |
| 155 |
self.MSG_WELCOME, |
| 156 |
self.session_id, |
| 157 |
1, |
| 158 |
'gevent-websocket/' + get_version() |
| 159 |
] |
| 160 |
self.app.ws.send(serialize(welcome)) |
| 161 |
|
| 162 |
def _get_exception_info(self, e): |
| 163 |
uri = 'http://TODO#generic' |
| 164 |
desc = str(type(e)) |
| 165 |
details = str(e) |
| 166 |
return [uri, desc, details] |
| 167 |
|
| 168 |
def rpc_call(self, data): |
| 169 |
call_id, curie_or_uri = data[1:3] |
| 170 |
args = data[3:] |
| 171 |
|
| 172 |
if not isinstance(call_id, string_types): |
| 173 |
raise Exception() |
| 174 |
if not isinstance(curie_or_uri, string_types): |
| 175 |
raise Exception() |
| 176 |
|
| 177 |
uri = self.prefixes.resolve(curie_or_uri) |
| 178 |
|
| 179 |
try: |
| 180 |
result = self.procedures.call(uri, args) |
| 181 |
result_msg = [self.MSG_CALL_RESULT, call_id, result] |
| 182 |
except Exception as e: |
| 183 |
result_msg = [self.MSG_CALL_ERROR, |
| 184 |
call_id] + self._get_exception_info(e) |
| 185 |
|
| 186 |
self.app.on_message(serialize(result_msg)) |
| 187 |
|
| 188 |
def pubsub_action(self, data): |
| 189 |
action = data[0] |
| 190 |
curie_or_uri = data[1] |
| 191 |
|
| 192 |
if not isinstance(action, int): |
| 193 |
raise Exception() |
| 194 |
if not isinstance(curie_or_uri, string_types): |
| 195 |
raise Exception() |
| 196 |
|
| 197 |
uri = self.prefixes.resolve(curie_or_uri) |
| 198 |
|
| 199 |
if action == self.MSG_SUBSCRIBE and len(data) == 2: |
| 200 |
self.server.channels.subscribe(data[1], self.handler.active_client) |
| 201 |
|
| 202 |
elif action == self.MSG_UNSUBSCRIBE and len(data) == 2: |
| 203 |
self.server.channels.unsubscribe( |
| 204 |
data[1], self.handler.active_client) |
| 205 |
|
| 206 |
elif action == self.MSG_PUBLISH and len(data) >= 3: |
| 207 |
payload = data[2] if len(data) >= 3 else None |
| 208 |
exclude = data[3] if len(data) >= 4 else None |
| 209 |
eligible = data[4] if len(data) >= 5 else None |
| 210 |
|
| 211 |
self.server.channels.publish(uri, payload, exclude, eligible) |
| 212 |
|
| 213 |
def on_open(self): |
| 214 |
self.app.on_open() |
| 215 |
self.do_handshake() |
| 216 |
|
| 217 |
def on_message(self, message): |
| 218 |
data = json.loads(message) |
| 219 |
|
| 220 |
if not isinstance(data, list): |
| 221 |
raise Exception('incoming data is no list') |
| 222 |
|
| 223 |
if data[0] == self.MSG_PREFIX and len(data) == 3: |
| 224 |
prefix, uri = data[1:3] |
| 225 |
self.prefixes.add(prefix, uri) |
| 226 |
|
| 227 |
elif data[0] == self.MSG_CALL and len(data) >= 3: |
| 228 |
return self.rpc_call(data) |
| 229 |
|
| 230 |
elif data[0] in (self.MSG_SUBSCRIBE, self.MSG_UNSUBSCRIBE, |
| 231 |
self.MSG_PUBLISH): |
| 232 |
return self.pubsub_action(data) |
| 233 |
else: |
| 234 |
raise Exception("Unknown call") |
| 235 |
|