Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@ jobs:
- "3.14t"
- "3.15"
- "3.15t"
os: [ubuntu-latest, macos-latest]
os: [ubuntu-latest, macos-latest, windows-latest]
exclude:
- os: 'ubuntu-latest'
python-version: '3.9'

env:
PIP_DISABLE_PIP_VERSION_CHECK: 1
Expand Down Expand Up @@ -70,7 +73,8 @@ jobs:
make test

- name: Test (debug build)
if: steps.release.outputs.version == 0
# windows doesn't have debuggers.
if: steps.release.outputs.version == 0 && matrix.os != 'windows-latest'
run: |
make distclean && make debug && make test

Expand Down
5 changes: 3 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@ classifiers = [
"Development Status :: 5 - Production/Stable",
"Framework :: AsyncIO",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"License :: OSI Approved :: MIT License",
# NOTE: OSI is deprecated
# "License :: OSI Approved :: Apache Software License",
# "License :: OSI Approved :: MIT License",
"Operating System :: POSIX",
"Operating System :: MacOS :: MacOS X",
"Programming Language :: Python :: 3 :: Only",
Expand Down
84 changes: 58 additions & 26 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@
if vi < (3, 9):
raise RuntimeError('uvloop requires Python 3.9 or greater')

if sys.platform in ('win32', 'cygwin', 'cli'):
raise RuntimeError('uvloop does not support Windows at the moment')

import os
import os.path
Expand All @@ -17,25 +15,26 @@
import subprocess
import sys

from setuptools import setup, Extension
from setuptools import Extension, setup
from setuptools.command.build_ext import build_ext
from setuptools.command.sdist import sdist


CYTHON_DEPENDENCY = 'Cython~=3.1'
# Windows likes the slash
O2_FLAG = '-O2' if sys.platform != "win32" else "/O2"
CYTHON_DEPENDENCY = 'Cython>=3.1'
MACHINE = platform.machine()
MODULES_CFLAGS = shlex.split(os.getenv('UVLOOP_OPT_CFLAGS', '-O2'))
MODULES_CFLAGS = shlex.split(os.getenv('UVLOOP_OPT_CFLAGS', O2_FLAG))
_ROOT = pathlib.Path(__file__).parent
LIBUV_DIR = str(_ROOT / 'vendor' / 'libuv')
LIBUV_BUILD_DIR = str(_ROOT / 'build' / 'libuv-{}'.format(MACHINE))
LIBUV_BUILD_DIR = str(_ROOT / 'build' / f'libuv-{MACHINE}')


def _libuv_build_env():
env = os.environ.copy()

cur_cflags = env.get('CFLAGS', '')
if not re.search(r'-O\d', cur_cflags):
cur_cflags += ' -O2'
cur_cflags += f' {O2_FLAG}'

env['CFLAGS'] = (cur_cflags + ' -fPIC ' + env.get('ARCHFLAGS', ''))

Expand All @@ -56,6 +55,22 @@ def _libuv_autogen(env):
['/bin/sh', 'autogen.sh'], cwd=LIBUV_DIR, env=env, check=True)


def _libuv_windows_autogen(ext: "uvloop_build_ext"):
"""sets up libuv to be compiled on windows"""
libuv = pathlib.Path("vendor", "libuv")
path = libuv / "src"
c_files = [p.as_posix() for p in path.iterdir() if p.suffix == ".c"]
c_files += [
p.as_posix() for p in (path / "win").iterdir() if p.suffix == ".c"
]
ext.extensions[-1].include_dirs.extend([
pathlib.Path("vendor", "libuv", "include").as_posix(),
path.as_posix(),
(path / "win").as_posix()
])
ext.extensions[-1].sources += c_files


class uvloop_sdist(sdist):
def run(self):
# Make sure sdist archive contains configure
Expand Down Expand Up @@ -96,7 +111,7 @@ def finalize_options(self):
for extension in self.distribution.ext_modules:
for i, sfile in enumerate(extension.sources):
if sfile.endswith('.pyx'):
prefix, ext = os.path.splitext(sfile)
prefix, _ = os.path.splitext(sfile)
cfile = prefix + '.c'

if os.path.exists(cfile) and not self.cython_always:
Expand All @@ -119,15 +134,12 @@ def finalize_options(self):
import Cython
except ImportError:
raise RuntimeError(
'please install {} to compile uvloop from source'.format(
CYTHON_DEPENDENCY))
f'please install {CYTHON_DEPENDENCY} to compile uvloop from source')

cython_dep = Requirement(CYTHON_DEPENDENCY)
if not cython_dep.specifier.contains(Cython.__version__):
raise RuntimeError(
'uvloop requires {}, got Cython=={}'.format(
CYTHON_DEPENDENCY, Cython.__version__
))
f'uvloop requires {CYTHON_DEPENDENCY}, got Cython=={Cython.__version__}')

from Cython.Build import cythonize

Expand All @@ -147,17 +159,19 @@ def finalize_options(self):
self.distribution.ext_modules,
compiler_directives=directives,
annotate=self.cython_annotate,
compile_time_env=dict(DEFAULT_FREELIST_SIZE=250),
compile_time_env={'DEFAULT_FREELIST_SIZE': 250},
emit_linenums=self.debug)

super().finalize_options()

def build_libuv(self):
env = _libuv_build_env()

# Make sure configure and friends are present in case
# we are building from a git checkout.
_libuv_autogen(env)
if sys.platform != 'win32':
# Make sure configure and friends are present in case
# we are building from a git checkout.
_libuv_autogen(env)


# Copy the libuv tree to build/ so that its build
# products don't pollute sdist accidentally.
Expand All @@ -184,7 +198,7 @@ def build_libuv(self):
njobs = len(os.sched_getaffinity(0))
except AttributeError:
njobs = os.cpu_count()
j_flag = '-j{}'.format(njobs or 1)
j_flag = f'-j{njobs or 1}'
c_flag = "CFLAGS={}".format(env['CFLAGS'])
subprocess.run(
['make', j_flag, c_flag],
Expand All @@ -198,6 +212,10 @@ def build_extensions(self):
os.path.exists('/opt/local/include'):
# Support macports on Mac OS X.
self.compiler.add_include_dir('/opt/local/include')
elif sys.platform.startswith("win"):
# Skip everything else below we can use CMake to do the job.
_libuv_windows_autogen(self)

else:
libuv_lib = os.path.join(LIBUV_BUILD_DIR, '.libs', 'libuv.a')
if not os.path.exists(libuv_lib):
Expand All @@ -215,7 +233,20 @@ def build_extensions(self):
elif sys.platform.startswith('sunos'):
self.compiler.add_library('kstat')

self.compiler.add_library('pthread')
elif sys.platform.startswith('win'):
self.compiler.add_library('advapi32')
self.compiler.add_library('iphlpapi')
self.compiler.add_library('psapi')
self.compiler.add_library('shell32')
self.compiler.add_library('user32')
self.compiler.add_library('userenv')
self.compiler.add_library('ws2_32')
self.compiler.add_library("ole32")
self.compiler.add_library("dbghelp")
self.compiler.add_library("synchronization")

if not sys.platform.startswith("win"):
self.compiler.add_library('pthread')

super().build_extensions()

Expand All @@ -231,11 +262,11 @@ def build_extensions(self):
'unable to read the version from uvloop/_version.py')


setup_requires = []
# setup_requires = []

if not (_ROOT / 'uvloop' / 'loop.c').exists() or '--cython-always' in sys.argv:
# No Cython output, require Cython to build.
setup_requires.append(CYTHON_DEPENDENCY)
# if not (_ROOT / 'uvloop' / 'loop.c').exists() or '--cython-always' in sys.argv:
# # No Cython output, require Cython to build.
# setup_requires.append(CYTHON_DEPENDENCY)


setup(
Expand All @@ -250,8 +281,9 @@ def build_extensions(self):
sources=[
"uvloop/loop.pyx",
],
extra_compile_args=MODULES_CFLAGS
extra_compile_args=MODULES_CFLAGS,
define_macros=[("WIN32_LEAN_AND_MEAN", "1"), ("_WIN32_WINNT", "0x0602")] if sys.platform == "win32" else []
),
],
setup_requires=setup_requires,
# setup_requires=setup_requires,
)
5 changes: 4 additions & 1 deletion tests/__main__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import multiprocessing
import os.path
import sys
import unittest
Expand All @@ -10,7 +11,9 @@ def suite():
return test_suite


if __name__ == '__main__':
if __name__ == "__main__":
if sys.platform == "win32":
multiprocessing.freeze_support()
runner = unittest.runner.TextTestRunner()
result = runner.run(suite())
sys.exit(not result.wasSuccessful())
51 changes: 28 additions & 23 deletions tests/test_aiohttp.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,32 +15,30 @@


class _TestAioHTTP:

def test_aiohttp_basic_1(self):

PAYLOAD = '<h1>It Works!</h1>' * 10000
PAYLOAD = "<h1>It Works!</h1>" * 10000

async def on_request(request):
return aiohttp.web.Response(text=PAYLOAD)

asyncio.set_event_loop(self.loop)
app = aiohttp.web.Application()
app.router.add_get('/', on_request)
app.router.add_get("/", on_request)

runner = aiohttp.web.AppRunner(app)
self.loop.run_until_complete(runner.setup())
site = aiohttp.web.TCPSite(runner, '0.0.0.0', '0')
site = aiohttp.web.TCPSite(runner, "0.0.0.0", "0")
self.loop.run_until_complete(site.start())
port = site._server.sockets[0].getsockname()[1]

async def test():
# Make sure we're using the correct event loop.
self.assertIs(asyncio.get_event_loop(), self.loop)

for addr in (('localhost', port),
('127.0.0.1', port)):
for addr in (("localhost", port), ("127.0.0.1", port)):
async with aiohttp.ClientSession() as client:
async with client.get('http://{}:{}'.format(*addr)) as r:
async with client.get("http://{}:{}".format(*addr)) as r:
self.assertEqual(r.status, 200)
result = await r.text()
self.assertEqual(result, PAYLOAD)
Expand All @@ -49,42 +47,43 @@ async def test():
self.loop.run_until_complete(runner.cleanup())

def test_aiohttp_graceful_shutdown(self):
if self.implementation == 'asyncio' and sys.version_info >= (3, 12, 0):
if self.implementation == "asyncio" and sys.version_info >= (3, 12, 0):
# In Python 3.12.0, asyncio.Server.wait_closed() waits for all
# existing connections to complete, before aiohttp sends
# on_shutdown signals.
# https://github.com/aio-libs/aiohttp/issues/7675#issuecomment-1752143748
# https://github.com/python/cpython/pull/98582
raise unittest.SkipTest('bug in aiohttp: #7675')
raise unittest.SkipTest("bug in aiohttp: #7675")

async def websocket_handler(request):
ws = aiohttp.web.WebSocketResponse()
await ws.prepare(request)
request.app['websockets'].add(ws)
request.app["websockets"].add(ws)
try:
async for msg in ws:
await ws.send_str(msg.data)
finally:
request.app['websockets'].discard(ws)
request.app["websockets"].discard(ws)
return ws

async def on_shutdown(app):
for ws in set(app['websockets']):
for ws in set(app["websockets"]):
await ws.close(
code=aiohttp.WSCloseCode.GOING_AWAY,
message='Server shutdown')
message="Server shutdown",
)

asyncio.set_event_loop(self.loop)
app = aiohttp.web.Application()
app.router.add_get('/', websocket_handler)
app.router.add_get("/", websocket_handler)
app.on_shutdown.append(on_shutdown)
app['websockets'] = weakref.WeakSet()
app["websockets"] = weakref.WeakSet()

runner = aiohttp.web.AppRunner(app)
self.loop.run_until_complete(runner.setup())
site = aiohttp.web.TCPSite(
runner,
'0.0.0.0',
"0.0.0.0",
0,
# https://github.com/aio-libs/aiohttp/pull/7188
shutdown_timeout=0.1,
Expand All @@ -93,12 +92,13 @@ async def on_shutdown(app):
port = site._server.sockets[0].getsockname()[1]

async def client():
async with aiohttp.ClientSession() as client:
async with client.ws_connect(
'http://127.0.0.1:{}'.format(port)) as ws:
await ws.send_str("hello")
async for msg in ws:
assert msg.data == "hello"
async with (
aiohttp.ClientSession() as client,
client.ws_connect(f"http://127.0.0.1:{port}") as ws,
):
await ws.send_str("hello")
async for msg in ws:
assert msg.data == "hello"

client_task = asyncio.ensure_future(client())

Expand All @@ -123,4 +123,9 @@ class Test_UV_AioHTTP(_TestAioHTTP, tb.UVTestCase):

@unittest.skipIf(skip_tests, "no aiohttp module")
class Test_AIO_AioHTTP(_TestAioHTTP, tb.AIOTestCase):
pass
# Winloop comment: switching to selector loop (instead of proactor),
# see https://github.com/saghul/aiodns/issues/86
if sys.platform == "win32":

def new_policy(self):
return asyncio.WindowsSelectorEventLoopPolicy()
Loading
Loading