|
| 1 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 2 | +# you may not use this file except in compliance with the License. |
| 3 | +# You may obtain a copy of the License at |
| 4 | +# |
| 5 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | +# |
| 7 | +# Unless required by applicable law or agreed to in writing, software |
| 8 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 9 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 10 | +# See the License for the specific language governing permissions and |
| 11 | +# limitations under the License. |
| 12 | + |
| 13 | +"""SSEClient module to handle streaming of realtime changes on the database |
| 14 | +to the firebase-admin-sdk |
| 15 | +""" |
| 16 | + |
| 17 | +import re |
| 18 | +import time |
| 19 | +import warnings |
| 20 | +import six |
| 21 | +import requests |
| 22 | + |
| 23 | + |
| 24 | +# Technically, we should support streams that mix line endings. This regex, |
| 25 | +# however, assumes that a system will provide consistent line endings. |
| 26 | +end_of_field = re.compile(r'\r\n\r\n|\r\r|\n\n') |
| 27 | + |
| 28 | + |
| 29 | +class KeepAuthSession(requests.Session): |
| 30 | + """A session that does not drop Authentication on redirects between domains""" |
| 31 | + def rebuild_auth(self, prepared_request, response): |
| 32 | + pass |
| 33 | + |
| 34 | + |
| 35 | +class SSEClient(object): |
| 36 | + """SSE Client Class""" |
| 37 | + |
| 38 | + def __init__(self, url, session, last_id=None, retry=3000, **kwargs): |
| 39 | + """Initialize the SSEClient |
| 40 | + Args: |
| 41 | + url: the url to connect to |
| 42 | + session: the requests.session() |
| 43 | + last_id: optional id |
| 44 | + retry: the interval in ms |
| 45 | + **kwargs: extra kwargs will be sent to requests.get |
| 46 | + """ |
| 47 | + self.should_connect = True |
| 48 | + self.url = url |
| 49 | + self.last_id = last_id |
| 50 | + self.retry = retry |
| 51 | + self.session = session |
| 52 | + self.requests_kwargs = kwargs |
| 53 | + |
| 54 | + headers = self.requests_kwargs.get('headers', {}) |
| 55 | + # The SSE spec requires making requests with Cache-Control: nocache |
| 56 | + headers['Cache-Control'] = 'no-cache' |
| 57 | + # The 'Accept' header is not required, but explicit > implicit |
| 58 | + headers['Accept'] = 'text/event-stream' |
| 59 | + |
| 60 | + self.requests_kwargs['headers'] = headers |
| 61 | + |
| 62 | + # Keep data here as it streams in |
| 63 | + self.buf = u'' |
| 64 | + |
| 65 | + self._connect() |
| 66 | + |
| 67 | + def close(self): |
| 68 | + """Close the SSE Client instance""" |
| 69 | + # TODO: check if AttributeError is needed to catch here |
| 70 | + self.should_connect = False |
| 71 | + self.retry = 0 |
| 72 | + self.resp.close() |
| 73 | + # self.resp.raw._fp.fp.raw._sock.shutdown(socket.SHUT_RDWR) |
| 74 | + # self.resp.raw._fp.fp.raw._sock.close() |
| 75 | + |
| 76 | + |
| 77 | + def _connect(self): |
| 78 | + """connects to the server using requests""" |
| 79 | + if self.should_connect: |
| 80 | + success = False |
| 81 | + while not success: |
| 82 | + if self.last_id: |
| 83 | + self.requests_kwargs['headers']['Last-Event-ID'] = self.last_id |
| 84 | + # Use session if set. Otherwise fall back to requests module. |
| 85 | + self.requester = self.session or requests |
| 86 | + self.resp = self.requester.get(self.url, stream=True, **self.requests_kwargs) |
| 87 | + |
| 88 | + self.resp_iterator = self.resp.iter_content(decode_unicode=True) |
| 89 | + |
| 90 | + # TODO: Ensure we're handling redirects. Might also stick the 'origin' |
| 91 | + # attribute on Events like the Javascript spec requires. |
| 92 | + self.resp.raise_for_status() |
| 93 | + success = True |
| 94 | + else: |
| 95 | + raise StopIteration() |
| 96 | + |
| 97 | + def _event_complete(self): |
| 98 | + """Checks if the event is completed by matching regular expression |
| 99 | +
|
| 100 | + Returns: |
| 101 | + boolean: True if the regex matched meaning end of event, else False |
| 102 | + """ |
| 103 | + return re.search(end_of_field, self.buf) is not None |
| 104 | + |
| 105 | + def __iter__(self): |
| 106 | + return self |
| 107 | + |
| 108 | + def __next__(self): |
| 109 | + while not self._event_complete(): |
| 110 | + try: |
| 111 | + nextchar = next(self.resp_iterator) |
| 112 | + self.buf += nextchar |
| 113 | + except (StopIteration, requests.RequestException): |
| 114 | + time.sleep(self.retry / 1000.0) |
| 115 | + self._connect() |
| 116 | + |
| 117 | + |
| 118 | + # The SSE spec only supports resuming from a whole message, so |
| 119 | + # if we have half a message we should throw it out. |
| 120 | + head, sep, tail = self.buf.rpartition('\n') |
| 121 | + self.buf = head + sep |
| 122 | + continue |
| 123 | + |
| 124 | + split = re.split(end_of_field, self.buf) |
| 125 | + head = split[0] |
| 126 | + tail = "".join(split[1:]) |
| 127 | + |
| 128 | + self.buf = tail |
| 129 | + msg = Event.parse(head) |
| 130 | + |
| 131 | + if msg.data == "credential is no longer valid": |
| 132 | + self._connect() |
| 133 | + return None |
| 134 | + |
| 135 | + if msg.data == 'null': |
| 136 | + return None |
| 137 | + |
| 138 | + # If the server requests a specific retry delay, we need to honor it. |
| 139 | + if msg.retry: |
| 140 | + self.retry = msg.retry |
| 141 | + |
| 142 | + # last_id should only be set if included in the message. It's not |
| 143 | + # forgotten if a message omits it. |
| 144 | + if msg.event_id: |
| 145 | + self.last_id = msg.event_id |
| 146 | + |
| 147 | + return msg |
| 148 | + |
| 149 | + if six.PY2: |
| 150 | + next = __next__ |
| 151 | + |
| 152 | + |
| 153 | +class Event(object): |
| 154 | + """Event class to handle the events fired by SSE""" |
| 155 | + |
| 156 | + sse_line_pattern = re.compile('(?P<name>[^:]*):?( ?(?P<value>.*))?') |
| 157 | + |
| 158 | + def __init__(self, data='', event='message', event_id=None, retry=None): |
| 159 | + self.data = data |
| 160 | + self.event = event |
| 161 | + self.event_id = event_id |
| 162 | + self.retry = retry |
| 163 | + |
| 164 | + @classmethod |
| 165 | + def parse(cls, raw): |
| 166 | + """Given a possibly-multiline string representing an SSE message, parse it |
| 167 | + and return a Event object. |
| 168 | +
|
| 169 | + Args: |
| 170 | + raw: the raw data to parse |
| 171 | +
|
| 172 | + Returns: |
| 173 | + Event: newly intialized Event() object with the parameters initialized |
| 174 | + """ |
| 175 | + msg = cls() |
| 176 | + for line in raw.split('\n'): |
| 177 | + match = cls.sse_line_pattern.match(line) |
| 178 | + if match is None: |
| 179 | + # Malformed line. Discard but warn. |
| 180 | + warnings.warn('Invalid SSE line: "%s"' % line, SyntaxWarning) |
| 181 | + continue |
| 182 | + |
| 183 | + name = match.groupdict()['name'] |
| 184 | + value = match.groupdict()['value'] |
| 185 | + if name == '': |
| 186 | + # line began with a ":", so is a comment. Ignore |
| 187 | + continue |
| 188 | + |
| 189 | + if name == 'data': |
| 190 | + # If we already have some data, then join to it with a newline. |
| 191 | + # Else this is it. |
| 192 | + if msg.data: |
| 193 | + msg.data = '%s\n%s' % (msg.data, value) |
| 194 | + else: |
| 195 | + msg.data = value |
| 196 | + elif name == 'event': |
| 197 | + msg.event = value |
| 198 | + elif name == 'id': |
| 199 | + msg.event_id = value |
| 200 | + elif name == 'retry': |
| 201 | + msg.retry = int(value) |
| 202 | + |
| 203 | + return msg |
| 204 | + |
| 205 | + def __str__(self): |
| 206 | + return self.data |
0 commit comments