|
| 1 | +# |
| 2 | +# Copyright (c) 2016 by nexB, Inc. http://www.nexb.com/ - All rights reserved. |
| 3 | +# |
| 4 | + |
| 5 | +from __future__ import absolute_import |
| 6 | +from __future__ import print_function |
| 7 | +from __future__ import unicode_literals |
| 8 | + |
| 9 | +from collections import OrderedDict |
| 10 | +from functools import wraps |
| 11 | +import inspect |
| 12 | +import re |
| 13 | + |
| 14 | + |
| 15 | +""" |
| 16 | +Given a URI regex (or some string), this module can route execution to a |
| 17 | +callable. |
| 18 | +
|
| 19 | +There are several routing implementations available in Rails, Django, Flask, |
| 20 | +Paste, etc. However, these all assume that the routed processing is to craft a |
| 21 | +response to an incoming external HTTP request. |
| 22 | +
|
| 23 | +Here we are instead doing the opposite: given a URI (and no request yet) we are |
| 24 | +routing the processing to emit a request externally (HTTP or other protocol) |
| 25 | +and handling its response. |
| 26 | +
|
| 27 | +Also we crawl a lot and not only HTTP: git, svn, ftp, rsync and more. |
| 28 | +This simple library support this kind of arbitrary URI routing. |
| 29 | +
|
| 30 | +This is inspired by Guido's http://www.artima.com/weblogs/viewpost.jsp?thread=101605 |
| 31 | +and Django, Flask, Werkzeug and other url dispatch and routing design from web |
| 32 | +frameworks. |
| 33 | +https://github.com/douban/brownant has a similar approach, using |
| 34 | +Werkzeug with the limitation that it does not route based on URI scheme and is |
| 35 | +limited to HTTP. |
| 36 | +""" |
| 37 | + |
| 38 | + |
| 39 | +class Rule(object): |
| 40 | + """ |
| 41 | + A rule is a mapping between a pattern (typically a URI) and a callable |
| 42 | + (typically a function). |
| 43 | + The pattern is a regex string pattern and must match entirely a string |
| 44 | + (typically a URI) for the rule to be considered, i.e. for the endpoint to |
| 45 | + be resolved and eventually invoked for a given string (typically a URI). |
| 46 | + """ |
| 47 | + def __init__(self, pattern, endpoint): |
| 48 | + # To ensure the pattern will match entirely, we wrap the pattern |
| 49 | + # with start of line ^ and end of line $. |
| 50 | + self.pattern = pattern.lstrip('^').rstrip('$') |
| 51 | + self.pattern_match = re.compile('^' + self.pattern + '$').match |
| 52 | + |
| 53 | + # ensure the endpoint is callable |
| 54 | + assert callable(endpoint) |
| 55 | + # classes are not always callable, make an extra check |
| 56 | + if inspect.isclass(endpoint): |
| 57 | + obj = endpoint() |
| 58 | + assert callable(obj) |
| 59 | + |
| 60 | + self.endpoint = endpoint |
| 61 | + |
| 62 | + def __repr__(self): |
| 63 | + return 'Rule(r"""{}""", {}.{})'.format( |
| 64 | + self.pattern, self.endpoint.__module__, self.endpoint.__name__) |
| 65 | + |
| 66 | + def match(self, string): |
| 67 | + """ |
| 68 | + Match a string with the rule pattern, return True is matching. |
| 69 | + """ |
| 70 | + return self.pattern_match(string) |
| 71 | + |
| 72 | + |
| 73 | +class RouteAlreadyDefined(TypeError): |
| 74 | + """ |
| 75 | + Raised when this route Rule already exists in the route map. |
| 76 | + """ |
| 77 | + |
| 78 | + |
| 79 | +class NoRouteAvailable(TypeError): |
| 80 | + """ |
| 81 | + Raised when there are no route available. |
| 82 | + """ |
| 83 | + |
| 84 | + |
| 85 | +class MultipleRoutesDefined(TypeError): |
| 86 | + """ |
| 87 | + Raised when there are more than one route possible. |
| 88 | + """ |
| 89 | + |
| 90 | + |
| 91 | +class Router(object): |
| 92 | + """ |
| 93 | + A router is: |
| 94 | + - a container for a route map, consisting of several rules, stored in an |
| 95 | + ordered dictionary keyed by pattern text |
| 96 | + - a way to process a route, i.e. given a string (typically a URI), find the |
| 97 | + correct rule and invoke its callable endpoint |
| 98 | + - and a convenience decorator for routed callables (either a function or |
| 99 | + something with a __call__ method) |
| 100 | +
|
| 101 | + Multiple routers can co-exist as needed, such as a router to collect, |
| 102 | + another to fetch, etc. |
| 103 | + """ |
| 104 | + def __init__(self, route_map=None): |
| 105 | + """ |
| 106 | + 'route_map' is an ordered mapping of pattern -> Rule. |
| 107 | + """ |
| 108 | + self.route_map = route_map or OrderedDict() |
| 109 | + # lazy cached pre-compiled regex match() for all route patterns |
| 110 | + self._is_routable = None |
| 111 | + |
| 112 | + def __repr__(self): |
| 113 | + return repr(self.route_map) |
| 114 | + |
| 115 | + def __iter__(self): |
| 116 | + return iter(self.route_map.items()) |
| 117 | + |
| 118 | + def keys(self): |
| 119 | + return self.route_map.keys() |
| 120 | + |
| 121 | + def append(self, pattern, endpoint): |
| 122 | + """ |
| 123 | + Append a new pattern and endpoint Rule at the end of the map. |
| 124 | + Use this as an alternative to the route decorator. |
| 125 | + """ |
| 126 | + if pattern in self.route_map: |
| 127 | + raise RouteAlreadyDefined(pattern) |
| 128 | + self.route_map[pattern] = Rule(pattern, endpoint) |
| 129 | + |
| 130 | + def route(self, *patterns): |
| 131 | + """ |
| 132 | + Decorator to make a callable 'endpoint' routed to one or more patterns. |
| 133 | +
|
| 134 | + Example: |
| 135 | + >>> my_router = Router() |
| 136 | + >>> @my_router.route('http://nexb.com', 'http://deja.com') |
| 137 | + ... def somefunc(uri): |
| 138 | + ... pass |
| 139 | + """ |
| 140 | + def decorator(endpoint): |
| 141 | + assert patterns |
| 142 | + for pat in patterns: |
| 143 | + self.append(pat, endpoint) |
| 144 | + |
| 145 | + @wraps(endpoint) |
| 146 | + def decorated(*args, **kwargs): |
| 147 | + return self.process(*args, **kwargs) |
| 148 | + return decorated |
| 149 | + |
| 150 | + return decorator |
| 151 | + |
| 152 | + def process(self, string, *args, **kwargs): |
| 153 | + """ |
| 154 | + Given a string (typically a URI), resolve this string to an endpoint |
| 155 | + by searching available rules then execute the endpoint callable for |
| 156 | + that string passing down all arguments to the endpoint invocation. |
| 157 | + """ |
| 158 | + endpoint = self.resolve(string) |
| 159 | + if inspect.isclass(endpoint): |
| 160 | + # instantiate a class, that must define a __call__ method |
| 161 | + # TODO: consider passing args to the constructor? |
| 162 | + endpoint = endpoint() |
| 163 | + # call the callable |
| 164 | + return endpoint(string, *args, **kwargs) |
| 165 | + |
| 166 | + def resolve(self, string): |
| 167 | + """ |
| 168 | + Resolve a string: given a string (typically a URI) resolve and |
| 169 | + return the best endpoint function for that string. |
| 170 | +
|
| 171 | + Ambiguous resolution is not allowed in order to keep things in |
| 172 | + check when there are hundreds rules: if multiple routes are |
| 173 | + possible for a string (typically a URI), a MultipleRoutesDefined |
| 174 | + TypeError is raised. |
| 175 | + """ |
| 176 | + # TODO: we could improve the performance of this by using a single |
| 177 | + # regex and named groups if this ever becomes a bottleneck. |
| 178 | + candidates = [r for r in self.route_map.values() if r.match(string)] |
| 179 | + |
| 180 | + if not candidates: |
| 181 | + raise NoRouteAvailable(string) |
| 182 | + |
| 183 | + if len(candidates) > 1: |
| 184 | + # this can happen when multiple patterns match the same string |
| 185 | + # we raise an exception with enough debugging information |
| 186 | + pats = repr([r.pattern for r in candidates]) |
| 187 | + msg = '%(string)r matches multiple patterns %(pats)r' % locals() |
| 188 | + raise MultipleRoutesDefined(msg) |
| 189 | + |
| 190 | + return candidates[0].endpoint |
| 191 | + |
| 192 | + def is_routable(self, string): |
| 193 | + """ |
| 194 | + Return True if `string` is routable by this router, e.g. if it |
| 195 | + matches any of the route patterns. |
| 196 | + """ |
| 197 | + if not string: |
| 198 | + return |
| 199 | + |
| 200 | + if not self._is_routable: |
| 201 | + # build an alternation regex |
| 202 | + routables = '^(' + '|'.join(pat for pat in self.route_map) + ')$' |
| 203 | + self._is_routable = re.compile(routables, re.UNICODE).match |
| 204 | + |
| 205 | + return bool(self._is_routable(string)) |
0 commit comments