Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

uri.py 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. ###############################################################################
  2. #
  3. # The MIT License (MIT)
  4. #
  5. # Copyright (c) typedef int GmbH
  6. #
  7. # Permission is hereby granted, free of charge, to any person obtaining a copy
  8. # of this software and associated documentation files (the "Software"), to deal
  9. # in the Software without restriction, including without limitation the rights
  10. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. # copies of the Software, and to permit persons to whom the Software is
  12. # furnished to do so, subject to the following conditions:
  13. #
  14. # The above copyright notice and this permission notice shall be included in
  15. # all copies or substantial portions of the Software.
  16. #
  17. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. # THE SOFTWARE.
  24. #
  25. ###############################################################################
  26. import re
  27. from typing import Optional, Union
  28. from autobahn.util import public
  29. from autobahn.wamp.types import RegisterOptions, SubscribeOptions
  30. __all__ = (
  31. 'Pattern',
  32. 'register',
  33. 'subscribe',
  34. 'error',
  35. 'convert_starred_uri'
  36. )
  37. def convert_starred_uri(uri: str):
  38. """
  39. Convert a starred URI to a standard WAMP URI and a detected matching
  40. policy. A starred URI is one that may contain the character '*' used
  41. to mark URI wildcard components or URI prefixes. Starred URIs are
  42. more comfortable / intuitive to use at the user/API level, but need
  43. to be converted for use on the wire (WAMP protocol level).
  44. This function takes a possibly starred URI, detects the matching policy
  45. implied by stars, and returns a pair (uri, match) with any stars
  46. removed from the URI and the detected matching policy.
  47. An URI like 'com.example.topic1' (without any stars in it) is
  48. detected as an exact-matching URI.
  49. An URI like 'com.example.*' (with exactly one star at the very end)
  50. is detected as a prefix-matching URI on 'com.example.'.
  51. An URI like 'com.*.foobar.*' (with more than one star anywhere) is
  52. detected as a wildcard-matching URI on 'com..foobar.' (in this example,
  53. there are two wildcard URI components).
  54. Note that an URI like 'com.example.*' is always detected as
  55. a prefix-matching URI 'com.example.'. You cannot express a wildcard-matching
  56. URI 'com.example.' using the starred URI notation! A wildcard matching on
  57. 'com.example.' is different from prefix-matching on 'com.example.' (which
  58. matches a strict superset of the former!). This is one reason we don't use
  59. starred URIs for WAMP at the protocol level.
  60. """
  61. assert(type(uri) == str)
  62. cnt_stars = uri.count('*')
  63. if cnt_stars == 0:
  64. match = 'exact'
  65. elif cnt_stars == 1 and uri[-1] == '*':
  66. match = 'prefix'
  67. uri = uri[:-1]
  68. else:
  69. match = 'wildcard'
  70. uri = uri.replace('*', '')
  71. return uri, match
  72. @public
  73. class Pattern(object):
  74. """
  75. A WAMP URI Pattern.
  76. .. todo::
  77. * suffix matches
  78. * args + kwargs
  79. * uuid converter
  80. * multiple URI patterns per decorated object
  81. * classes: Pattern, EndpointPattern, ..
  82. """
  83. URI_TARGET_ENDPOINT = 1
  84. URI_TARGET_HANDLER = 2
  85. URI_TARGET_EXCEPTION = 3
  86. URI_TYPE_EXACT = 1
  87. URI_TYPE_PREFIX = 2
  88. URI_TYPE_WILDCARD = 3
  89. _URI_COMPONENT = re.compile(r"^[a-z0-9][a-z0-9_\-]*$")
  90. """
  91. Compiled regular expression for a WAMP URI component.
  92. """
  93. _URI_NAMED_COMPONENT = re.compile(r"^<([a-z][a-z0-9_]*)>$")
  94. """
  95. Compiled regular expression for a named WAMP URI component.
  96. .. note::
  97. This pattern is stricter than a general WAMP URI component since a valid Python identifier is required.
  98. """
  99. _URI_NAMED_CONVERTED_COMPONENT = re.compile(r"^<([a-z][a-z0-9_]*):([a-z]*)>$")
  100. """
  101. Compiled regular expression for a named and type-converted WAMP URI component.
  102. .. note::
  103. This pattern is stricter than a general WAMP URI component since a valid Python identifier is required.
  104. """
  105. def __init__(self, uri: str, target: int, options: Optional[Union[SubscribeOptions, RegisterOptions]] = None,
  106. check_types: Optional[bool] = None):
  107. """
  108. :param uri: The URI or URI pattern, e.g. ``"com.myapp.product.<product:int>.update"``.
  109. :type uri: str
  110. :param target: The target for this pattern: a procedure endpoint (a callable),
  111. an event handler (a callable) or an exception (a class).
  112. :type target: callable or obj
  113. :param options: An optional options object
  114. :type options: None or RegisterOptions or SubscribeOptions
  115. :param check_types: Enable automatic type checking against (Python 3.5+) type hints
  116. specified on the ``endpoint`` callable. Types are checked at run-time on each
  117. invocation of the ``endpoint`` callable. When a type mismatch occurs, the error
  118. is forwarded to the callee code in ``onUserError`` override method of
  119. :class:`autobahn.wamp.protocol.ApplicationSession`. An error
  120. of type :class:`autobahn.wamp.exception.TypeCheckError` is also raised and
  121. returned to the caller (via the router).
  122. :type check_types: bool
  123. """
  124. assert (type(uri) == str)
  125. assert (len(uri) > 0)
  126. assert (target in [Pattern.URI_TARGET_ENDPOINT,
  127. Pattern.URI_TARGET_HANDLER,
  128. Pattern.URI_TARGET_EXCEPTION])
  129. if target == Pattern.URI_TARGET_ENDPOINT:
  130. assert (options is None or type(options) == RegisterOptions)
  131. elif target == Pattern.URI_TARGET_HANDLER:
  132. assert (options is None or type(options) == SubscribeOptions)
  133. else:
  134. options = None
  135. components = uri.split('.')
  136. _URI_COMP_CHARS = r'[^\s\.#]+'
  137. # _URI_COMP_CHARS = r'[\da-z_]+'
  138. # _URI_COMP_CHARS = r'[a-z0-9][a-z0-9_\-]*'
  139. pl = []
  140. nc = {}
  141. group_count = 0
  142. for i in range(len(components)):
  143. component = components[i]
  144. match = Pattern._URI_NAMED_CONVERTED_COMPONENT.match(component)
  145. if match:
  146. name, comp_type = match.groups()
  147. if comp_type not in ['str', 'string', 'int', 'suffix']:
  148. raise TypeError("invalid URI")
  149. if comp_type == 'suffix' and i != len(components) - 1:
  150. raise TypeError("invalid URI")
  151. if name in nc:
  152. raise TypeError("invalid URI")
  153. if comp_type in ['str', 'string', 'suffix']:
  154. nc[name] = str
  155. elif comp_type == 'int':
  156. nc[name] = int
  157. else:
  158. # should not arrive here
  159. raise TypeError("logic error")
  160. pl.append("(?P<{}>{})".format(name, _URI_COMP_CHARS))
  161. group_count += 1
  162. continue
  163. match = Pattern._URI_NAMED_COMPONENT.match(component)
  164. if match:
  165. name = match.groups()[0]
  166. if name in nc:
  167. raise TypeError("invalid URI")
  168. nc[name] = str
  169. pl.append("(?P<{}>{})".format(name, _URI_COMP_CHARS))
  170. group_count += 1
  171. continue
  172. match = Pattern._URI_COMPONENT.match(component)
  173. if match:
  174. pl.append(component)
  175. continue
  176. if component == '':
  177. group_count += 1
  178. pl.append(r"({})".format(_URI_COMP_CHARS))
  179. nc[group_count] = str
  180. continue
  181. raise TypeError("invalid URI")
  182. if nc:
  183. # URI pattern
  184. self._type = Pattern.URI_TYPE_WILDCARD
  185. p = "^" + r"\.".join(pl) + "$"
  186. self._pattern = re.compile(p)
  187. self._names = nc
  188. else:
  189. # exact URI
  190. self._type = Pattern.URI_TYPE_EXACT
  191. self._pattern = None
  192. self._names = None
  193. self._uri = uri
  194. self._target = target
  195. self._options = options
  196. self._check_types = check_types
  197. @public
  198. @property
  199. def options(self):
  200. """
  201. Returns the Options instance (if present) for this pattern.
  202. :return: None or the Options instance
  203. :rtype: None or RegisterOptions or SubscribeOptions
  204. """
  205. return self._options
  206. @public
  207. @property
  208. def uri_type(self):
  209. """
  210. Returns the URI type of this pattern
  211. :return:
  212. :rtype: Pattern.URI_TYPE_EXACT, Pattern.URI_TYPE_PREFIX or Pattern.URI_TYPE_WILDCARD
  213. """
  214. return self._type
  215. @public
  216. def uri(self):
  217. """
  218. Returns the original URI (pattern) for this pattern.
  219. :returns: The URI (pattern), e.g. ``"com.myapp.product.<product:int>.update"``.
  220. :rtype: str
  221. """
  222. return self._uri
  223. def match(self, uri):
  224. """
  225. Match the given (fully qualified) URI according to this pattern
  226. and return extracted args and kwargs.
  227. :param uri: The URI to match, e.g. ``"com.myapp.product.123456.update"``.
  228. :type uri: str
  229. :returns: A tuple ``(args, kwargs)``
  230. :rtype: tuple
  231. """
  232. args = []
  233. kwargs = {}
  234. if self._type == Pattern.URI_TYPE_EXACT:
  235. return args, kwargs
  236. elif self._type == Pattern.URI_TYPE_WILDCARD:
  237. match = self._pattern.match(uri)
  238. if match:
  239. for key in self._names:
  240. val = match.group(key)
  241. val = self._names[key](val)
  242. kwargs[key] = val
  243. return args, kwargs
  244. else:
  245. raise ValueError('no match')
  246. @public
  247. def is_endpoint(self):
  248. """
  249. Check if this pattern is for a procedure endpoint.
  250. :returns: ``True``, iff this pattern is for a procedure endpoint.
  251. :rtype: bool
  252. """
  253. return self._target == Pattern.URI_TARGET_ENDPOINT
  254. @public
  255. def is_handler(self):
  256. """
  257. Check if this pattern is for an event handler.
  258. :returns: ``True``, iff this pattern is for an event handler.
  259. :rtype: bool
  260. """
  261. return self._target == Pattern.URI_TARGET_HANDLER
  262. @public
  263. def is_exception(self):
  264. """
  265. Check if this pattern is for an exception.
  266. :returns: ``True``, iff this pattern is for an exception.
  267. :rtype: bool
  268. """
  269. return self._target == Pattern.URI_TARGET_EXCEPTION
  270. @public
  271. def register(uri: Optional[str], options: Optional[RegisterOptions] = None, check_types: Optional[bool] = None):
  272. """
  273. Decorator for WAMP procedure endpoints.
  274. :param uri:
  275. :type uri: str
  276. :param options:
  277. :type options: None or RegisterOptions
  278. :param check_types: Enable automatic type checking against (Python 3.5+) type hints
  279. specified on the ``endpoint`` callable. Types are checked at run-time on each
  280. invocation of the ``endpoint`` callable. When a type mismatch occurs, the error
  281. is forwarded to the callee code in ``onUserError`` override method of
  282. :class:`autobahn.wamp.protocol.ApplicationSession`. An error
  283. of type :class:`autobahn.wamp.exception.TypeCheckError` is also raised and
  284. returned to the caller (via the router).
  285. :type check_types: bool
  286. """
  287. def decorate(f):
  288. assert(callable(f))
  289. if uri is None:
  290. real_uri = '{}'.format(f.__name__)
  291. else:
  292. real_uri = uri
  293. if not hasattr(f, '_wampuris'):
  294. f._wampuris = []
  295. f._wampuris.append(Pattern(real_uri, Pattern.URI_TARGET_ENDPOINT, options, check_types))
  296. return f
  297. return decorate
  298. @public
  299. def subscribe(uri: Optional[str], options: Optional[SubscribeOptions] = None, check_types: Optional[bool] = None):
  300. """
  301. Decorator for WAMP event handlers.
  302. :param uri:
  303. :type uri: str
  304. :param options:
  305. :type options: None or SubscribeOptions
  306. :param check_types: Enable automatic type checking against (Python 3.5+) type hints
  307. specified on the ``endpoint`` callable. Types are checked at run-time on each
  308. invocation of the ``endpoint`` callable. When a type mismatch occurs, the error
  309. is forwarded to the callee code in ``onUserError`` override method of
  310. :class:`autobahn.wamp.protocol.ApplicationSession`. An error
  311. of type :class:`autobahn.wamp.exception.TypeCheckError` is also raised and
  312. returned to the caller (via the router).
  313. :type check_types: bool
  314. """
  315. def decorate(f):
  316. assert(callable(f))
  317. if not hasattr(f, '_wampuris'):
  318. f._wampuris = []
  319. f._wampuris.append(Pattern(uri, Pattern.URI_TARGET_HANDLER, options, check_types))
  320. return f
  321. return decorate
  322. @public
  323. def error(uri: str):
  324. """
  325. Decorator for WAMP error classes.
  326. """
  327. def decorate(cls):
  328. assert(issubclass(cls, Exception))
  329. if not hasattr(cls, '_wampuris'):
  330. cls._wampuris = []
  331. cls._wampuris.append(Pattern(uri, Pattern.URI_TARGET_EXCEPTION))
  332. return cls
  333. return decorate