-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpoll_loop.py
More file actions
441 lines (352 loc) · 12 KB
/
poll_loop.py
File metadata and controls
441 lines (352 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
"""Defines a custom `asyncio` event loop backed by `wasi:io/poll#poll`.
This also includes helper classes and functions for working with `wasi:http`.
As of WASI Preview 2, there is not yet a standard for first-class, composable
asynchronous functions and streams. We expect that little or none of this
boilerplate will be needed once those features arrive in Preview 3.
"""
import asyncio
import socket
import subprocess
from componentize_py_types import Ok, Err
from wit_world.imports import types, streams, poll, outgoing_handler
from wit_world.imports.types import (
IncomingBody,
OutgoingBody,
OutgoingRequest,
IncomingResponse,
)
from wit_world.imports.streams import StreamError_Closed, InputStream
from wit_world.imports.poll import Pollable
from typing import Optional, cast
# Maximum number of bytes to read at a time
READ_SIZE: int = 16 * 1024
async def send(request: OutgoingRequest) -> IncomingResponse:
"""Send the specified request and wait asynchronously for the response."""
future = outgoing_handler.handle(request, None)
while True:
response = future.get()
if response is None:
await register(cast(PollLoop, asyncio.get_event_loop()), future.subscribe())
else:
if isinstance(response, Ok):
if isinstance(response.value, Ok):
return response.value.value
else:
raise response.value
else:
raise response
class Stream:
"""Reader abstraction over `wasi:http/types#incoming-body`."""
def __init__(self, body: IncomingBody):
self.body: Optional[IncomingBody] = body
self.stream: Optional[InputStream] = body.stream()
async def next(self) -> Optional[bytes]:
"""Wait for the next chunk of data to arrive on the stream.
This will return `None` when the end of the stream has been reached.
"""
while True:
try:
if self.stream is None:
return None
else:
buffer = self.stream.read(READ_SIZE)
if len(buffer) == 0:
await register(
cast(PollLoop, asyncio.get_event_loop()),
self.stream.subscribe(),
)
else:
return buffer
except Err as e:
if isinstance(e.value, StreamError_Closed):
if self.stream is not None:
self.stream.__exit__(None, None, None)
self.stream = None
if self.body is not None:
IncomingBody.finish(self.body)
self.body = None
else:
raise e
class Sink:
"""Writer abstraction over `wasi:http/types#outgoing-body`."""
def __init__(self, body: OutgoingBody):
self.body = body
self.stream = body.write()
async def send(self, chunk: bytes):
"""Write the specified bytes to the sink.
This may need to yield according to the backpressure requirements of the sink.
"""
offset = 0
flushing = False
while True:
count = self.stream.check_write()
if count == 0:
await register(
cast(PollLoop, asyncio.get_event_loop()), self.stream.subscribe()
)
elif offset == len(chunk):
if flushing:
return
else:
self.stream.flush()
flushing = True
else:
count = min(count, len(chunk) - offset)
self.stream.write(chunk[offset : offset + count])
offset += count
def close(self):
"""Close the stream, indicating no further data will be written."""
self.stream.__exit__(None, None, None)
self.stream = None
OutgoingBody.finish(self.body, None)
self.body = None
class PollLoop(asyncio.AbstractEventLoop):
"""Custom `asyncio` event loop backed by `wasi:io/poll#poll`."""
def __init__(self):
self.wakers = []
self.running = False
self.handles = []
self.exception = None
def get_debug(self):
return False
def run_until_complete(self, future):
future = asyncio.ensure_future(future, loop=self)
self.running = True
asyncio.events._set_running_loop(self)
while self.running and not future.done():
handles = self.handles
self.handles = []
for handle in handles:
if not handle._cancelled:
handle._run()
if self.wakers:
[pollables, wakers] = list(map(list, zip(*self.wakers)))
new_wakers = []
ready = [False] * len(pollables)
for index in poll.poll(pollables):
ready[index] = True
for (ready, pollable), waker in zip(zip(ready, pollables), wakers):
if ready:
pollable.__exit__(None, None, None)
waker.set_result(None)
else:
new_wakers.append((pollable, waker))
self.wakers = new_wakers
if self.exception is not None:
raise self.exception
return future.result()
def is_running(self):
return self.running
def is_closed(self):
return not self.running
def stop(self):
self.running = False
def close(self):
self.running = False
def shutdown_asyncgens(self):
pass
def call_exception_handler(self, context):
self.exception = context.get("exception", None)
def call_soon(self, callback, *args, context=None):
handle = asyncio.Handle(callback, args, self, context)
self.handles.append(handle)
return handle
def create_task(self, coroutine):
return asyncio.Task(coroutine, loop=self)
def create_future(self):
return asyncio.Future(loop=self)
# The remaining methods should be irrelevant for our purposes and thus unimplemented
def run_forever(self):
raise NotImplementedError
async def shutdown_default_executor(self):
raise NotImplementedError
def _timer_handle_cancelled(self, handle):
raise NotImplementedError
def call_later(self, delay, callback, *args, context=None):
raise NotImplementedError
def call_at(self, when, callback, *args, context=None):
raise NotImplementedError
def time(self):
raise NotImplementedError
def call_soon_threadsafe(self, callback, *args, context=None):
raise NotImplementedError
def run_in_executor(self, executor, func, *args):
raise NotImplementedError
def set_default_executor(self, executor):
raise NotImplementedError
async def getaddrinfo(self, host, port, *, family=0, type=0, proto=0, flags=0):
raise NotImplementedError
async def getnameinfo(self, sockaddr, flags=0):
raise NotImplementedError
async def create_connection(
self,
protocol_factory,
host=None,
port=None,
*,
ssl=None,
family=0,
proto=0,
flags=0,
sock=None,
local_addr=None,
server_hostname=None,
ssl_handshake_timeout=None,
ssl_shutdown_timeout=None,
happy_eyeballs_delay=None,
interleave=None,
):
raise NotImplementedError
async def create_server(
self,
protocol_factory,
host=None,
port=None,
*,
family=socket.AF_UNSPEC,
flags=socket.AI_PASSIVE,
sock=None,
backlog=100,
ssl=None,
reuse_address=None,
reuse_port=None,
ssl_handshake_timeout=None,
ssl_shutdown_timeout=None,
start_serving=True,
):
raise NotImplementedError
async def sendfile(self, transport, file, offset=0, count=None, *, fallback=True):
raise NotImplementedError
async def start_tls(
self,
transport,
protocol,
sslcontext,
*,
server_side=False,
server_hostname=None,
ssl_handshake_timeout=None,
ssl_shutdown_timeout=None,
):
raise NotImplementedError
async def create_unix_connection(
self,
protocol_factory,
path=None,
*,
ssl=None,
sock=None,
server_hostname=None,
ssl_handshake_timeout=None,
ssl_shutdown_timeout=None,
):
raise NotImplementedError
async def create_unix_server(
self,
protocol_factory,
path=None,
*,
sock=None,
backlog=100,
ssl=None,
ssl_handshake_timeout=None,
ssl_shutdown_timeout=None,
start_serving=True,
):
raise NotImplementedError
async def connect_accepted_socket(
self,
protocol_factory,
sock,
*,
ssl=None,
ssl_handshake_timeout=None,
ssl_shutdown_timeout=None,
):
raise NotImplementedError
async def create_datagram_endpoint(
self,
protocol_factory,
local_addr=None,
remote_addr=None,
*,
family=0,
proto=0,
flags=0,
reuse_address=None,
reuse_port=None,
allow_broadcast=None,
sock=None,
):
raise NotImplementedError
async def connect_read_pipe(self, protocol_factory, pipe):
raise NotImplementedError
async def connect_write_pipe(self, protocol_factory, pipe):
raise NotImplementedError
async def subprocess_shell(
self,
protocol_factory,
cmd,
*,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
**kwargs,
):
raise NotImplementedError
async def subprocess_exec(
self,
protocol_factory,
*args,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
**kwargs,
):
raise NotImplementedError
def add_reader(self, fd, callback, *args):
raise NotImplementedError
def remove_reader(self, fd):
raise NotImplementedError
def add_writer(self, fd, callback, *args):
raise NotImplementedError
def remove_writer(self, fd):
raise NotImplementedError
async def sock_recv(self, sock, nbytes):
raise NotImplementedError
async def sock_recv_into(self, sock, buf):
raise NotImplementedError
async def sock_recvfrom(self, sock, bufsize):
raise NotImplementedError
async def sock_recvfrom_into(self, sock, buf, nbytes=0):
raise NotImplementedError
async def sock_sendall(self, sock, data):
raise NotImplementedError
async def sock_sendto(self, sock, data, address):
raise NotImplementedError
async def sock_connect(self, sock, address):
raise NotImplementedError
async def sock_accept(self, sock):
raise NotImplementedError
async def sock_sendfile(self, sock, file, offset=0, count=None, *, fallback=None):
raise NotImplementedError
def add_signal_handler(self, sig, callback, *args):
raise NotImplementedError
def remove_signal_handler(self, sig):
raise NotImplementedError
def set_task_factory(self, factory):
raise NotImplementedError
def get_task_factory(self):
raise NotImplementedError
def get_exception_handler(self):
raise NotImplementedError
def set_exception_handler(self, handler):
raise NotImplementedError
def default_exception_handler(self, context):
raise NotImplementedError
def set_debug(self, enabled):
raise NotImplementedError
async def register(loop: PollLoop, pollable: Pollable):
waker = loop.create_future()
loop.wakers.append((pollable, waker))
await waker