|
| 1 | +import uerrno |
| 2 | +import uselect as select |
| 3 | +import usocket as _socket |
| 4 | +from uasyncio.core import * |
| 5 | + |
| 6 | + |
| 7 | +DEBUG = 0 |
| 8 | +log = None |
| 9 | + |
| 10 | +def set_debug(val): |
| 11 | + global DEBUG, log |
| 12 | + DEBUG = val |
| 13 | + if val: |
| 14 | + import logging |
| 15 | + log = logging.getLogger("uasyncio") |
| 16 | + |
| 17 | + |
| 18 | +class PollEventLoop(EventLoop): |
| 19 | + |
| 20 | + def __init__(self, runq_len=16, waitq_len=16): |
| 21 | + EventLoop.__init__(self, runq_len, waitq_len) |
| 22 | + self.poller = select.poll() |
| 23 | + self.objmap = {} |
| 24 | + |
| 25 | + def add_reader(self, sock, cb, *args): |
| 26 | + if DEBUG and __debug__: |
| 27 | + log.debug("add_reader%s", (sock, cb, args)) |
| 28 | + if args: |
| 29 | + self.poller.register(sock, select.POLLIN) |
| 30 | + self.objmap[id(sock)] = (cb, args) |
| 31 | + else: |
| 32 | + self.poller.register(sock, select.POLLIN) |
| 33 | + self.objmap[id(sock)] = cb |
| 34 | + |
| 35 | + def remove_reader(self, sock): |
| 36 | + if DEBUG and __debug__: |
| 37 | + log.debug("remove_reader(%s)", sock) |
| 38 | + self.poller.unregister(sock) |
| 39 | + del self.objmap[id(sock)] |
| 40 | + |
| 41 | + def add_writer(self, sock, cb, *args): |
| 42 | + if DEBUG and __debug__: |
| 43 | + log.debug("add_writer%s", (sock, cb, args)) |
| 44 | + if args: |
| 45 | + self.poller.register(sock, select.POLLOUT) |
| 46 | + self.objmap[id(sock)] = (cb, args) |
| 47 | + else: |
| 48 | + self.poller.register(sock, select.POLLOUT) |
| 49 | + self.objmap[id(sock)] = cb |
| 50 | + |
| 51 | + def remove_writer(self, sock): |
| 52 | + if DEBUG and __debug__: |
| 53 | + log.debug("remove_writer(%s)", sock) |
| 54 | + try: |
| 55 | + self.poller.unregister(sock) |
| 56 | + self.objmap.pop(id(sock), None) |
| 57 | + except OSError as e: |
| 58 | + # StreamWriter.awrite() first tries to write to a socket, |
| 59 | + # and if that succeeds, yield IOWrite may never be called |
| 60 | + # for that socket, and it will never be added to poller. So, |
| 61 | + # ignore such error. |
| 62 | + if e.args[0] != uerrno.ENOENT: |
| 63 | + raise |
| 64 | + |
| 65 | + def wait(self, delay): |
| 66 | + if DEBUG and __debug__: |
| 67 | + log.debug("poll.wait(%d)", delay) |
| 68 | + # We need one-shot behavior (second arg of 1 to .poll()) |
| 69 | + res = self.poller.ipoll(delay, 1) |
| 70 | + #log.debug("poll result: %s", res) |
| 71 | + # Remove "if res" workaround after |
| 72 | + # https://github.com/micropython/micropython/issues/2716 fixed. |
| 73 | + if res: |
| 74 | + for sock, ev in res: |
| 75 | + cb = self.objmap[id(sock)] |
| 76 | + if ev & (select.POLLHUP | select.POLLERR): |
| 77 | + # These events are returned even if not requested, and |
| 78 | + # are sticky, i.e. will be returned again and again. |
| 79 | + # If the caller doesn't do proper error handling and |
| 80 | + # unregister this sock, we'll busy-loop on it, so we |
| 81 | + # as well can unregister it now "just in case". |
| 82 | + self.remove_reader(sock) |
| 83 | + if DEBUG and __debug__: |
| 84 | + log.debug("Calling IO callback: %r", cb) |
| 85 | + if isinstance(cb, tuple): |
| 86 | + cb[0](*cb[1]) |
| 87 | + else: |
| 88 | + cb.pend_throw(None) |
| 89 | + self.call_soon(cb) |
| 90 | + |
| 91 | + |
| 92 | +class StreamReader: |
| 93 | + |
| 94 | + def __init__(self, polls, ios=None): |
| 95 | + if ios is None: |
| 96 | + ios = polls |
| 97 | + self.polls = polls |
| 98 | + self.ios = ios |
| 99 | + |
| 100 | + def read(self, n=-1): |
| 101 | + while True: |
| 102 | + yield IORead(self.polls) |
| 103 | + res = self.ios.read(n) |
| 104 | + if res is not None: |
| 105 | + break |
| 106 | + # This should not happen for real sockets, but can easily |
| 107 | + # happen for stream wrappers (ssl, websockets, etc.) |
| 108 | + #log.warn("Empty read") |
| 109 | + if not res: |
| 110 | + yield IOReadDone(self.polls) |
| 111 | + return res |
| 112 | + |
| 113 | + def readexactly(self, n): |
| 114 | + buf = b"" |
| 115 | + while n: |
| 116 | + yield IORead(self.polls) |
| 117 | + res = self.ios.read(n) |
| 118 | + assert res is not None |
| 119 | + if not res: |
| 120 | + yield IOReadDone(self.polls) |
| 121 | + break |
| 122 | + buf += res |
| 123 | + n -= len(res) |
| 124 | + return buf |
| 125 | + |
| 126 | + def readline(self): |
| 127 | + if DEBUG and __debug__: |
| 128 | + log.debug("StreamReader.readline()") |
| 129 | + buf = b"" |
| 130 | + while True: |
| 131 | + yield IORead(self.polls) |
| 132 | + res = self.ios.readline() |
| 133 | + assert res is not None |
| 134 | + if not res: |
| 135 | + yield IOReadDone(self.polls) |
| 136 | + break |
| 137 | + buf += res |
| 138 | + if buf[-1] == 0x0a: |
| 139 | + break |
| 140 | + if DEBUG and __debug__: |
| 141 | + log.debug("StreamReader.readline(): %s", buf) |
| 142 | + return buf |
| 143 | + |
| 144 | + def aclose(self): |
| 145 | + yield IOReadDone(self.polls) |
| 146 | + self.ios.close() |
| 147 | + |
| 148 | + def __repr__(self): |
| 149 | + return "<StreamReader %r %r>" % (self.polls, self.ios) |
| 150 | + |
| 151 | + |
| 152 | +class StreamWriter: |
| 153 | + |
| 154 | + def __init__(self, s, extra): |
| 155 | + self.s = s |
| 156 | + self.extra = extra |
| 157 | + |
| 158 | + def awrite(self, buf, off=0, sz=-1): |
| 159 | + # This method is called awrite (async write) to not proliferate |
| 160 | + # incompatibility with original asyncio. Unlike original asyncio |
| 161 | + # whose .write() method is both not a coroutine and guaranteed |
| 162 | + # to return immediately (which means it has to buffer all the |
| 163 | + # data), this method is a coroutine. |
| 164 | + if sz == -1: |
| 165 | + sz = len(buf) - off |
| 166 | + if DEBUG and __debug__: |
| 167 | + log.debug("StreamWriter.awrite(): spooling %d bytes", sz) |
| 168 | + while True: |
| 169 | + res = self.s.write(buf, off, sz) |
| 170 | + # If we spooled everything, return immediately |
| 171 | + if res == sz: |
| 172 | + if DEBUG and __debug__: |
| 173 | + log.debug("StreamWriter.awrite(): completed spooling %d bytes", res) |
| 174 | + return |
| 175 | + if res is None: |
| 176 | + res = 0 |
| 177 | + if DEBUG and __debug__: |
| 178 | + log.debug("StreamWriter.awrite(): spooled partial %d bytes", res) |
| 179 | + assert res < sz |
| 180 | + off += res |
| 181 | + sz -= res |
| 182 | + yield IOWrite(self.s) |
| 183 | + #assert s2.fileno() == self.s.fileno() |
| 184 | + if DEBUG and __debug__: |
| 185 | + log.debug("StreamWriter.awrite(): can write more") |
| 186 | + |
| 187 | + # Write piecewise content from iterable (usually, a generator) |
| 188 | + def awriteiter(self, iterable): |
| 189 | + for buf in iterable: |
| 190 | + yield from self.awrite(buf) |
| 191 | + |
| 192 | + def aclose(self): |
| 193 | + yield IOWriteDone(self.s) |
| 194 | + self.s.close() |
| 195 | + |
| 196 | + def get_extra_info(self, name, default=None): |
| 197 | + return self.extra.get(name, default) |
| 198 | + |
| 199 | + def __repr__(self): |
| 200 | + return "<StreamWriter %r>" % self.s |
| 201 | + |
| 202 | + |
| 203 | +def open_connection(host, port, ssl=False): |
| 204 | + if DEBUG and __debug__: |
| 205 | + log.debug("open_connection(%s, %s)", host, port) |
| 206 | + ai = _socket.getaddrinfo(host, port, 0, _socket.SOCK_STREAM) |
| 207 | + ai = ai[0] |
| 208 | + s = _socket.socket(ai[0], ai[1], ai[2]) |
| 209 | + s.setblocking(False) |
| 210 | + try: |
| 211 | + s.connect(ai[-1]) |
| 212 | + except OSError as e: |
| 213 | + if e.args[0] != uerrno.EINPROGRESS: |
| 214 | + raise |
| 215 | + if DEBUG and __debug__: |
| 216 | + log.debug("open_connection: After connect") |
| 217 | + yield IOWrite(s) |
| 218 | +# if __debug__: |
| 219 | +# assert s2.fileno() == s.fileno() |
| 220 | + if DEBUG and __debug__: |
| 221 | + log.debug("open_connection: After iowait: %s", s) |
| 222 | + if ssl: |
| 223 | + print("Warning: uasyncio SSL support is alpha") |
| 224 | + import ussl |
| 225 | + s.setblocking(True) |
| 226 | + s2 = ussl.wrap_socket(s) |
| 227 | + s.setblocking(False) |
| 228 | + return StreamReader(s, s2), StreamWriter(s2, {}) |
| 229 | + return StreamReader(s), StreamWriter(s, {}) |
| 230 | + |
| 231 | + |
| 232 | +def start_server(client_coro, host, port, backlog=10): |
| 233 | + if DEBUG and __debug__: |
| 234 | + log.debug("start_server(%s, %s)", host, port) |
| 235 | + ai = _socket.getaddrinfo(host, port, 0, _socket.SOCK_STREAM) |
| 236 | + ai = ai[0] |
| 237 | + s = _socket.socket(ai[0], ai[1], ai[2]) |
| 238 | + s.setblocking(False) |
| 239 | + |
| 240 | + s.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, 1) |
| 241 | + s.bind(ai[-1]) |
| 242 | + s.listen(backlog) |
| 243 | + while True: |
| 244 | + if DEBUG and __debug__: |
| 245 | + log.debug("start_server: Before accept") |
| 246 | + yield IORead(s) |
| 247 | + if DEBUG and __debug__: |
| 248 | + log.debug("start_server: After iowait") |
| 249 | + s2, client_addr = s.accept() |
| 250 | + s2.setblocking(False) |
| 251 | + if DEBUG and __debug__: |
| 252 | + log.debug("start_server: After accept: %s", s2) |
| 253 | + extra = {"peername": client_addr} |
| 254 | + yield client_coro(StreamReader(s2), StreamWriter(s2, extra)) |
| 255 | + |
| 256 | + |
| 257 | +import uasyncio.core |
| 258 | +uasyncio.core._event_loop_class = PollEventLoop |
0 commit comments