winloop 0.8.2__cp315-cp315-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. winloop/__init__.py +223 -0
  2. winloop/__pyinstaller/__init__.py +5 -0
  3. winloop/__pyinstaller/hook-winloop.py +6 -0
  4. winloop/_noop.py +3 -0
  5. winloop/_testbase.py +555 -0
  6. winloop/_version.py +13 -0
  7. winloop/cbhandles.pxd +39 -0
  8. winloop/cbhandles.pyx +448 -0
  9. winloop/dns.pyx +561 -0
  10. winloop/errors.pyx +139 -0
  11. winloop/future.pxd +36 -0
  12. winloop/future.pyx +271 -0
  13. winloop/handles/async_.pxd +11 -0
  14. winloop/handles/async_.pyx +56 -0
  15. winloop/handles/basetransport.pxd +54 -0
  16. winloop/handles/basetransport.pyx +293 -0
  17. winloop/handles/check.pxd +14 -0
  18. winloop/handles/check.pyx +72 -0
  19. winloop/handles/fsevent.pxd +12 -0
  20. winloop/handles/fsevent.pyx +116 -0
  21. winloop/handles/handle.pxd +48 -0
  22. winloop/handles/handle.pyx +395 -0
  23. winloop/handles/idle.pxd +14 -0
  24. winloop/handles/idle.pyx +72 -0
  25. winloop/handles/pipe.pxd +33 -0
  26. winloop/handles/pipe.pyx +247 -0
  27. winloop/handles/poll.pxd +25 -0
  28. winloop/handles/poll.pyx +237 -0
  29. winloop/handles/process.pxd +82 -0
  30. winloop/handles/process.pyx +871 -0
  31. winloop/handles/stream.pxd +58 -0
  32. winloop/handles/stream.pyx +1078 -0
  33. winloop/handles/streamserver.pxd +26 -0
  34. winloop/handles/streamserver.pyx +150 -0
  35. winloop/handles/tcp.pxd +26 -0
  36. winloop/handles/tcp.pyx +228 -0
  37. winloop/handles/timer.pxd +18 -0
  38. winloop/handles/timer.pyx +89 -0
  39. winloop/handles/udp.pxd +22 -0
  40. winloop/handles/udp.pyx +412 -0
  41. winloop/includes/__init__.py +23 -0
  42. winloop/includes/consts.pxi +33 -0
  43. winloop/includes/debug.pxd +3 -0
  44. winloop/includes/flowcontrol.pxd +23 -0
  45. winloop/includes/python.pxd +33 -0
  46. winloop/includes/stdlib.pxi +213 -0
  47. winloop/includes/system.pxd +116 -0
  48. winloop/includes/uv.pxd +522 -0
  49. winloop/loop.cp315-win_amd64.pyd +0 -0
  50. winloop/loop.pxd +251 -0
  51. winloop/loop.pyi +303 -0
  52. winloop/loop.pyx +3514 -0
  53. winloop/lru.pyx +79 -0
  54. winloop/pseudosock.pyx +209 -0
  55. winloop/py.typed +0 -0
  56. winloop/request.pxd +8 -0
  57. winloop/request.pyx +65 -0
  58. winloop/server.pxd +19 -0
  59. winloop/server.pyx +134 -0
  60. winloop/sslproto.pxd +144 -0
  61. winloop/sslproto.pyx +1007 -0
  62. winloop/weakref_set.pxd +28 -0
  63. winloop/weakref_set.pyx +271 -0
  64. winloop-0.8.2.dist-info/METADATA +161 -0
  65. winloop-0.8.2.dist-info/RECORD +70 -0
  66. winloop-0.8.2.dist-info/WHEEL +5 -0
  67. winloop-0.8.2.dist-info/entry_points.txt +2 -0
  68. winloop-0.8.2.dist-info/licenses/LICENSE-APACHE +203 -0
  69. winloop-0.8.2.dist-info/licenses/LICENSE-MIT +21 -0
  70. winloop-0.8.2.dist-info/top_level.txt +1 -0
winloop/_testbase.py ADDED
@@ -0,0 +1,555 @@
1
+ """Test utilities. Don't use outside of the winloop project."""
2
+
3
+
4
+ import asyncio
5
+ import asyncio.events
6
+ import collections
7
+ import contextlib
8
+ import gc
9
+ import logging
10
+ import os
11
+ import pprint
12
+ import re
13
+ import select
14
+ import socket
15
+ import ssl
16
+ import sys
17
+ import tempfile
18
+ import threading
19
+ import time
20
+ import unittest
21
+ import winloop
22
+
23
+
24
+ class MockPattern(str):
25
+ def __eq__(self, other):
26
+ return bool(re.search(str(self), other, re.S))
27
+
28
+
29
+ class TestCaseDict(collections.UserDict):
30
+
31
+ def __init__(self, name):
32
+ super().__init__()
33
+ self.name = name
34
+
35
+ def __setitem__(self, key, value):
36
+ if key in self.data:
37
+ raise RuntimeError('duplicate test {}.{}'.format(
38
+ self.name, key))
39
+ super().__setitem__(key, value)
40
+
41
+
42
+ class BaseTestCaseMeta(type):
43
+
44
+ @classmethod
45
+ def __prepare__(mcls, name, bases):
46
+ return TestCaseDict(name)
47
+
48
+ def __new__(mcls, name, bases, dct):
49
+ for test_name in dct:
50
+ if not test_name.startswith('test_'):
51
+ continue
52
+ for base in bases:
53
+ if hasattr(base, test_name):
54
+ raise RuntimeError(
55
+ 'duplicate test {}.{} (also defined in {} '
56
+ 'parent class)'.format(
57
+ name, test_name, base.__name__))
58
+
59
+ return super().__new__(mcls, name, bases, dict(dct))
60
+
61
+
62
+ class BaseTestCase(unittest.TestCase, metaclass=BaseTestCaseMeta):
63
+
64
+ def new_loop(self):
65
+ raise NotImplementedError
66
+
67
+ def new_policy(self):
68
+ raise NotImplementedError
69
+
70
+ def mock_pattern(self, str):
71
+ return MockPattern(str)
72
+
73
+ async def wait_closed(self, obj):
74
+ if not isinstance(obj, asyncio.StreamWriter):
75
+ return
76
+ try:
77
+ await obj.wait_closed()
78
+ except (BrokenPipeError, ConnectionError):
79
+ pass
80
+
81
+ def is_asyncio_loop(self):
82
+ return type(self.loop).__module__.startswith('asyncio.')
83
+
84
+ def run_loop_briefly(self, *, delay=0.01):
85
+ self.loop.run_until_complete(asyncio.sleep(delay))
86
+
87
+ def loop_exception_handler(self, loop, context):
88
+ self.__unhandled_exceptions.append(context)
89
+ self.loop.default_exception_handler(context)
90
+
91
+ def setUp(self):
92
+ # WINLOOP comment: next two lines are swapped because otherwise
93
+ # setting event loop policy has no effect.
94
+ asyncio.set_event_loop_policy(self.new_policy())
95
+ self.loop = self.new_loop()
96
+ asyncio.set_event_loop(self.loop)
97
+ self._check_unclosed_resources_in_debug = True
98
+
99
+ self.loop.set_exception_handler(self.loop_exception_handler)
100
+ self.__unhandled_exceptions = []
101
+
102
+ def tearDown(self):
103
+ self.loop.close()
104
+
105
+ if self.__unhandled_exceptions:
106
+ print('Unexpected calls to loop.call_exception_handler():')
107
+ pprint.pprint(self.__unhandled_exceptions)
108
+ self.fail('unexpected calls to loop.call_exception_handler()')
109
+ return
110
+
111
+ if not self._check_unclosed_resources_in_debug:
112
+ return
113
+
114
+ # GC to show any resource warnings as the test completes
115
+ gc.collect()
116
+ gc.collect()
117
+ gc.collect()
118
+
119
+ if getattr(self.loop, '_debug_cc', False):
120
+ gc.collect()
121
+ gc.collect()
122
+ gc.collect()
123
+
124
+ self.assertEqual(
125
+ self.loop._debug_uv_handles_total,
126
+ self.loop._debug_uv_handles_freed,
127
+ 'not all uv_handle_t handles were freed')
128
+
129
+ self.assertEqual(
130
+ self.loop._debug_cb_handles_count, 0,
131
+ 'not all callbacks (call_soon) are GCed')
132
+
133
+ self.assertEqual(
134
+ self.loop._debug_cb_timer_handles_count, 0,
135
+ 'not all timer callbacks (call_later) are GCed')
136
+
137
+ self.assertEqual(
138
+ self.loop._debug_stream_write_ctx_cnt, 0,
139
+ 'not all stream write contexts are GCed')
140
+
141
+ for h_name, h_cnt in self.loop._debug_handles_current.items():
142
+ with self.subTest('Alive handle after test',
143
+ handle_name=h_name):
144
+ self.assertEqual(
145
+ h_cnt, 0,
146
+ 'alive {} after test'.format(h_name))
147
+
148
+ for h_name, h_cnt in self.loop._debug_handles_total.items():
149
+ with self.subTest('Total/closed handles',
150
+ handle_name=h_name):
151
+ self.assertEqual(
152
+ h_cnt, self.loop._debug_handles_closed[h_name],
153
+ 'total != closed for {}'.format(h_name))
154
+
155
+ asyncio.set_event_loop(None)
156
+ asyncio.set_event_loop_policy(None)
157
+ self.loop = None
158
+
159
+ def skip_unclosed_handles_check(self):
160
+ self._check_unclosed_resources_in_debug = False
161
+
162
+ def tcp_server(self, server_prog, *,
163
+ family=socket.AF_INET,
164
+ addr=None,
165
+ timeout=5,
166
+ backlog=1,
167
+ max_clients=10):
168
+
169
+ if addr is None:
170
+ # Winloop comment: Windows has no Unix sockets
171
+ if hasattr(socket, "AF_UNIX") and family == socket.AF_UNIX:
172
+ with tempfile.NamedTemporaryFile() as tmp:
173
+ addr = tmp.name
174
+ else:
175
+ addr = ('127.0.0.1', 0)
176
+
177
+ sock = socket.socket(family, socket.SOCK_STREAM)
178
+
179
+ if timeout is None:
180
+ raise RuntimeError('timeout is required')
181
+ if timeout <= 0:
182
+ raise RuntimeError('only blocking sockets are supported')
183
+ sock.settimeout(timeout)
184
+
185
+ try:
186
+ sock.bind(addr)
187
+ sock.listen(backlog)
188
+ except OSError as ex:
189
+ sock.close()
190
+ raise ex
191
+
192
+ return TestThreadedServer(
193
+ self, sock, server_prog, timeout, max_clients)
194
+
195
+ def tcp_client(self, client_prog,
196
+ family=socket.AF_INET,
197
+ timeout=10):
198
+
199
+ sock = socket.socket(family, socket.SOCK_STREAM)
200
+
201
+ if timeout is None:
202
+ raise RuntimeError('timeout is required')
203
+ if timeout <= 0:
204
+ raise RuntimeError('only blocking sockets are supported')
205
+ sock.settimeout(timeout)
206
+
207
+ return TestThreadedClient(
208
+ self, sock, client_prog, timeout)
209
+
210
+ def unix_server(self, *args, **kwargs):
211
+ return self.tcp_server(*args, family=socket.AF_UNIX, **kwargs)
212
+
213
+ def unix_client(self, *args, **kwargs):
214
+ return self.tcp_client(*args, family=socket.AF_UNIX, **kwargs)
215
+
216
+ @contextlib.contextmanager
217
+ def unix_sock_name(self):
218
+ with tempfile.TemporaryDirectory() as td:
219
+ fn = os.path.join(td, 'sock')
220
+ try:
221
+ yield fn
222
+ finally:
223
+ try:
224
+ os.unlink(fn)
225
+ except OSError:
226
+ pass
227
+
228
+ def _abort_socket_test(self, ex):
229
+ try:
230
+ self.loop.stop()
231
+ finally:
232
+ self.fail(ex)
233
+
234
+
235
+ def _cert_fullname(test_file_name, cert_file_name):
236
+ fullname = os.path.abspath(os.path.join(
237
+ os.path.dirname(test_file_name), 'certs', cert_file_name))
238
+ assert os.path.isfile(fullname)
239
+ return fullname
240
+
241
+
242
+ @contextlib.contextmanager
243
+ def silence_long_exec_warning():
244
+
245
+ class Filter(logging.Filter):
246
+ def filter(self, record):
247
+ return not (record.msg.startswith('Executing') and
248
+ record.msg.endswith('seconds'))
249
+
250
+ logger = logging.getLogger('asyncio')
251
+ filter = Filter()
252
+ logger.addFilter(filter)
253
+ try:
254
+ yield
255
+ finally:
256
+ logger.removeFilter(filter)
257
+
258
+
259
+ def find_free_port(start_from=50000):
260
+ for port in range(start_from, start_from + 500):
261
+ sock = socket.socket()
262
+ with sock:
263
+ try:
264
+ sock.bind(('', port))
265
+ except socket.error:
266
+ continue
267
+ else:
268
+ return port
269
+ raise RuntimeError('could not find a free port')
270
+
271
+
272
+ class SSLTestCase:
273
+
274
+ def _create_server_ssl_context(self, certfile, keyfile=None):
275
+ if hasattr(ssl, 'PROTOCOL_TLS_SERVER'):
276
+ sslcontext = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
277
+ elif hasattr(ssl, 'PROTOCOL_TLS'):
278
+ sslcontext = ssl.SSLContext(ssl.PROTOCOL_TLS)
279
+ else:
280
+ sslcontext = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
281
+ sslcontext.options |= ssl.OP_NO_SSLv2
282
+ sslcontext.load_cert_chain(certfile, keyfile)
283
+ return sslcontext
284
+
285
+ def _create_client_ssl_context(self, *, disable_verify=True):
286
+ sslcontext = ssl.create_default_context()
287
+ sslcontext.check_hostname = False
288
+ if disable_verify:
289
+ sslcontext.verify_mode = ssl.CERT_NONE
290
+ return sslcontext
291
+
292
+ @contextlib.contextmanager
293
+ def _silence_eof_received_warning(self):
294
+ # TODO This warning has to be fixed in asyncio.
295
+ logger = logging.getLogger('asyncio')
296
+ filter = logging.Filter('has no effect when using ssl')
297
+ logger.addFilter(filter)
298
+ try:
299
+ yield
300
+ finally:
301
+ logger.removeFilter(filter)
302
+
303
+
304
+ class UVTestCase(BaseTestCase):
305
+
306
+ implementation = 'winloop'
307
+
308
+ def new_loop(self):
309
+ return winloop.new_event_loop()
310
+
311
+ def new_policy(self):
312
+ return winloop.EventLoopPolicy()
313
+
314
+
315
+ class AIOTestCase(BaseTestCase):
316
+
317
+ implementation = 'asyncio'
318
+
319
+ def setUp(self):
320
+ super().setUp()
321
+
322
+ if sys.version_info < (3, 12) and sys.platform != "win32":
323
+ watcher = asyncio.SafeChildWatcher()
324
+ watcher.attach_loop(self.loop)
325
+ asyncio.set_child_watcher(watcher)
326
+
327
+ def tearDown(self):
328
+ if sys.version_info < (3, 12) and sys.platform != "win32":
329
+ asyncio.set_child_watcher(None)
330
+ super().tearDown()
331
+
332
+ def new_loop(self):
333
+ return asyncio.new_event_loop()
334
+
335
+ def new_policy(self):
336
+ return asyncio.DefaultEventLoopPolicy()
337
+
338
+
339
+ def has_IPv6():
340
+ server_sock = socket.socket(socket.AF_INET6)
341
+ with server_sock:
342
+ try:
343
+ server_sock.bind(('::1', 0))
344
+ except OSError:
345
+ return False
346
+ else:
347
+ return True
348
+
349
+
350
+ has_IPv6 = has_IPv6()
351
+
352
+
353
+ ###############################################################################
354
+ # Socket Testing Utilities
355
+ ###############################################################################
356
+
357
+
358
+ class TestSocketWrapper:
359
+
360
+ def __init__(self, sock):
361
+ self.__sock = sock
362
+
363
+ def recv_all(self, n):
364
+ buf = b''
365
+ while len(buf) < n:
366
+ data = self.recv(n - len(buf))
367
+ if data == b'':
368
+ raise ConnectionAbortedError
369
+ buf += data
370
+ return buf
371
+
372
+ def starttls(self, ssl_context, *,
373
+ server_side=False,
374
+ server_hostname=None,
375
+ do_handshake_on_connect=True):
376
+
377
+ assert isinstance(ssl_context, ssl.SSLContext)
378
+
379
+ ssl_sock = ssl_context.wrap_socket(
380
+ self.__sock, server_side=server_side,
381
+ server_hostname=server_hostname,
382
+ do_handshake_on_connect=do_handshake_on_connect)
383
+
384
+ if server_side:
385
+ ssl_sock.do_handshake()
386
+
387
+ self.__sock.close()
388
+ self.__sock = ssl_sock
389
+
390
+ def __getattr__(self, name):
391
+ return getattr(self.__sock, name)
392
+
393
+ def __repr__(self):
394
+ return '<{} {!r}>'.format(type(self).__name__, self.__sock)
395
+
396
+
397
+ class SocketThread(threading.Thread):
398
+
399
+ def stop(self):
400
+ self._active = False
401
+ self.join()
402
+
403
+ def __enter__(self):
404
+ self.start()
405
+ return self
406
+
407
+ def __exit__(self, *exc):
408
+ self.stop()
409
+
410
+
411
+ class TestThreadedClient(SocketThread):
412
+
413
+ def __init__(self, test, sock, prog, timeout):
414
+ threading.Thread.__init__(self, None, None, 'test-client')
415
+ self.daemon = True
416
+
417
+ self._timeout = timeout
418
+ self._sock = sock
419
+ self._active = True
420
+ self._prog = prog
421
+ self._test = test
422
+
423
+ def run(self):
424
+ try:
425
+ self._prog(TestSocketWrapper(self._sock))
426
+ except (KeyboardInterrupt, SystemExit):
427
+ raise
428
+ except BaseException as ex:
429
+ self._test._abort_socket_test(ex)
430
+
431
+
432
+ class TestThreadedServer(SocketThread):
433
+
434
+ def __init__(self, test, sock, prog, timeout, max_clients):
435
+ threading.Thread.__init__(self, None, None, 'test-server')
436
+ self.daemon = True
437
+
438
+ self._clients = 0
439
+ self._finished_clients = 0
440
+ self._max_clients = max_clients
441
+ self._timeout = timeout
442
+ self._sock = sock
443
+ self._active = True
444
+
445
+ self._prog = prog
446
+
447
+ self._s1, self._s2 = socket.socketpair()
448
+ self._s1.setblocking(False)
449
+
450
+ self._test = test
451
+
452
+ def stop(self):
453
+ try:
454
+ if self._s2 and self._s2.fileno() != -1:
455
+ try:
456
+ self._s2.send(b'stop')
457
+ except OSError:
458
+ pass
459
+ finally:
460
+ super().stop()
461
+
462
+ def run(self):
463
+ try:
464
+ with self._sock:
465
+ self._sock.setblocking(0)
466
+ self._run()
467
+ finally:
468
+ self._s1.close()
469
+ self._s2.close()
470
+
471
+ def _run(self):
472
+ while self._active:
473
+ if self._clients >= self._max_clients:
474
+ return
475
+
476
+ r, w, x = select.select(
477
+ [self._sock, self._s1], [], [], self._timeout)
478
+
479
+ if self._s1 in r:
480
+ return
481
+
482
+ if self._sock in r:
483
+ try:
484
+ conn, addr = self._sock.accept()
485
+ except BlockingIOError:
486
+ continue
487
+ except socket.timeout:
488
+ if not self._active:
489
+ return
490
+ else:
491
+ raise
492
+ else:
493
+ self._clients += 1
494
+ conn.settimeout(self._timeout)
495
+ try:
496
+ with conn:
497
+ self._handle_client(conn)
498
+ except (KeyboardInterrupt, SystemExit):
499
+ raise
500
+ except BaseException as ex:
501
+ self._active = False
502
+ try:
503
+ raise
504
+ finally:
505
+ self._test._abort_socket_test(ex)
506
+
507
+ def _handle_client(self, sock):
508
+ self._prog(TestSocketWrapper(sock))
509
+
510
+ @property
511
+ def addr(self):
512
+ return self._sock.getsockname()
513
+
514
+
515
+ ###############################################################################
516
+ # A few helpers from asyncio/tests/testutils.py
517
+ ###############################################################################
518
+
519
+
520
+ def run_briefly(loop):
521
+ async def once():
522
+ pass
523
+ gen = once()
524
+ t = loop.create_task(gen)
525
+ # Don't log a warning if the task is not done after run_until_complete().
526
+ # It occurs if the loop is stopped or if a task raises a BaseException.
527
+ t._log_destroy_pending = False
528
+ try:
529
+ loop.run_until_complete(t)
530
+ finally:
531
+ gen.close()
532
+
533
+
534
+ def run_until(loop, pred, timeout=30):
535
+ deadline = time.time() + timeout
536
+ while not pred():
537
+ if timeout is not None:
538
+ timeout = deadline - time.time()
539
+ if timeout <= 0:
540
+ raise asyncio.futures.TimeoutError()
541
+ loop.run_until_complete(asyncio.tasks.sleep(0.001))
542
+
543
+
544
+ @contextlib.contextmanager
545
+ def disable_logger():
546
+ """Context manager to disable asyncio logger.
547
+
548
+ For example, it can be used to ignore warnings in debug mode.
549
+ """
550
+ old_level = asyncio.log.logger.level
551
+ try:
552
+ asyncio.log.logger.setLevel(logging.CRITICAL + 1)
553
+ yield
554
+ finally:
555
+ asyncio.log.logger.setLevel(old_level)
winloop/_version.py ADDED
@@ -0,0 +1,13 @@
1
+ # This file MUST NOT contain anything but the __version__ assignment.
2
+ #
3
+ # When making a release, change the value of __version__
4
+ # to an appropriate value, and open a pull request against
5
+ # the correct branch (master if making a new feature release).
6
+ # The commit message MUST contain a properly formatted release
7
+ # log, and the commit must be signed.
8
+ #
9
+ # The release automation will: build and test the packages for the
10
+ # supported platforms, publish the packages on PyPI, merge the PR
11
+ # to the target branch, create a Git tag pointing to the commit.
12
+
13
+ __version__ = '0.8.2'
winloop/cbhandles.pxd ADDED
@@ -0,0 +1,39 @@
1
+ cdef class Handle:
2
+ cdef:
3
+ Loop loop
4
+ object context
5
+ bint _cancelled
6
+
7
+ str meth_name
8
+ int cb_type
9
+ void *callback
10
+ object arg1, arg2, arg3, arg4
11
+
12
+ object __weakref__
13
+
14
+ readonly _source_traceback
15
+
16
+ cdef inline _set_loop(self, Loop loop)
17
+ cdef inline _set_context(self, object context)
18
+
19
+ cdef inline _run(self)
20
+ cdef _cancel(self)
21
+
22
+ cdef _format_handle(self)
23
+
24
+
25
+ cdef class TimerHandle:
26
+ cdef:
27
+ object callback
28
+ tuple args
29
+ bint _cancelled
30
+ UVTimer timer
31
+ Loop loop
32
+ object context
33
+ tuple _debug_info
34
+ object __weakref__
35
+ object _when
36
+
37
+ cdef _run(self)
38
+ cdef _cancel(self)
39
+ cdef inline _clear(self)