| 1 |
import functools |
| 2 |
import threading |
| 3 |
import time |
| 4 |
import types |
| 5 |
|
| 6 |
import pytest |
| 7 |
|
| 8 |
from caio import ( |
| 9 |
linux_aio, |
| 10 |
linux_aio_asyncio, |
| 11 |
linux_uring, |
| 12 |
linux_uring_asyncio, |
| 13 |
python_aio, |
| 14 |
thread_aio, |
| 15 |
variants, |
| 16 |
variants_asyncio, |
| 17 |
) |
| 18 |
|
| 19 |
|
| 20 |
class ConcurrentThreads: |
| 21 |
"""Run test workers and surface their failures in the main thread.""" |
| 22 |
|
| 23 |
def __init__(self, timeout=30): |
| 24 |
self.timeout = timeout |
| 25 |
self._barriers = [] |
| 26 |
self._threads = [] |
| 27 |
self._errors = [] |
| 28 |
self._errors_lock = threading.Lock() |
| 29 |
|
| 30 |
def barrier(self, parties): |
| 31 |
barrier = threading.Barrier(parties, timeout=self.timeout) |
| 32 |
self._barriers.append(barrier) |
| 33 |
return barrier |
| 34 |
|
| 35 |
def start(self, target, *args): |
| 36 |
thread = threading.Thread( |
| 37 |
target=self._run, |
| 38 |
args=(target, args), |
| 39 |
name=f"{target.__name__}-{len(self._threads)}", |
| 40 |
) |
| 41 |
self._threads.append(thread) |
| 42 |
thread.start() |
| 43 |
return thread |
| 44 |
|
| 45 |
def start_many(self, target, arguments): |
| 46 |
for args in arguments: |
| 47 |
self.start(target, *args) |
| 48 |
|
| 49 |
def join(self, timeout=None): |
| 50 |
deadline = time.monotonic() + ( |
| 51 |
self.timeout if timeout is None else timeout |
| 52 |
) |
| 53 |
for thread in self._threads: |
| 54 |
thread.join(max(0, deadline - time.monotonic())) |
| 55 |
|
| 56 |
alive = [thread.name for thread in self._threads if thread.is_alive()] |
| 57 |
assert not alive, f"worker threads did not stop: {', '.join(alive)}" |
| 58 |
if self._errors: |
| 59 |
raise self._errors[0] |
| 60 |
|
| 61 |
def close(self): |
| 62 |
for barrier in self._barriers: |
| 63 |
barrier.abort() |
| 64 |
for thread in self._threads: |
| 65 |
thread.join(timeout=5) |
| 66 |
|
| 67 |
def _run(self, target, args): |
| 68 |
try: |
| 69 |
target(*args) |
| 70 |
except BaseException as exc: # noqa: BLE001 (surface child-thread failures) |
| 71 |
with self._errors_lock: |
| 72 |
self._errors.append(exc) |
| 73 |
for barrier in self._barriers: |
| 74 |
barrier.abort() |
| 75 |
|
| 76 |
|
| 77 |
@pytest.fixture |
| 78 |
def workers(): |
| 79 |
threads = ConcurrentThreads() |
| 80 |
yield threads |
| 81 |
threads.close() |
| 82 |
|
| 83 |
|
| 84 |
@pytest.fixture |
| 85 |
def submit_and_wait(): |
| 86 |
def submit(context, operations, result_for=None, timeout=10): |
| 87 |
operations = tuple(operations) |
| 88 |
count = len(operations) |
| 89 |
results = [None] * count |
| 90 |
remaining = [count] |
| 91 |
errors = [] |
| 92 |
lock = threading.Lock() |
| 93 |
done = threading.Event() |
| 94 |
|
| 95 |
if result_for is None: |
| 96 |
result_for = lambda _operation, result: result |
| 97 |
|
| 98 |
def make_callback(index, operation): |
| 99 |
def callback(result): |
| 100 |
with lock: |
| 101 |
try: |
| 102 |
results[index] = result_for(operation, result) |
| 103 |
except BaseException as exc: # noqa: BLE001 (surface callback failures) |
| 104 |
errors.append(exc) |
| 105 |
finally: |
| 106 |
remaining[0] -= 1 |
| 107 |
if remaining[0] == 0: |
| 108 |
done.set() |
| 109 |
|
| 110 |
return callback |
| 111 |
|
| 112 |
for index, operation in enumerate(operations): |
| 113 |
operation.set_callback(make_callback(index, operation)) |
| 114 |
assert context.submit(operation) == 1 |
| 115 |
|
| 116 |
assert done.wait(timeout), ( |
| 117 |
f"only {count - remaining[0]}/{count} operations completed" |
| 118 |
) |
| 119 |
if errors: |
| 120 |
raise errors[0] |
| 121 |
return results |
| 122 |
|
| 123 |
return submit |
| 124 |
|
| 125 |
|
| 126 |
def named_variant(name, **attrs): |
| 127 |
ns = types.SimpleNamespace(__name__=name, **attrs) |
| 128 |
return ns |
| 129 |
|
| 130 |
|
| 131 |
# Test-only sqpoll/deferred variants - not part of caio's public API. |
| 132 |
extra_context_variants = [] |
| 133 |
extra_asyncio_variants = [] |
| 134 |
|
| 135 |
if linux_uring is not None: |
| 136 |
extra_context_variants.append(named_variant( |
| 137 |
"linux_uring[sqpoll=True]", |
| 138 |
Context=functools.partial(linux_uring.Context, sqpoll=True), |
| 139 |
Operation=linux_uring.Operation, |
| 140 |
)) |
| 141 |
extra_asyncio_variants.append(named_variant( |
| 142 |
"linux_uring[sqpoll=True]", |
| 143 |
AsyncioContext=functools.partial(linux_uring_asyncio.AsyncioContext, sqpoll=True), |
| 144 |
)) |
| 145 |
# sqpoll=False forced: SQPOLL_ALLOWED's default would otherwise mask |
| 146 |
# the deferred-batching path this variant exists to cover. |
| 147 |
extra_asyncio_variants.append(named_variant( |
| 148 |
"linux_uring[deferred=True]", |
| 149 |
AsyncioContext=functools.partial( |
| 150 |
linux_uring_asyncio.AsyncioContext, sqpoll=False, deferred=True, |
| 151 |
), |
| 152 |
)) |
| 153 |
|
| 154 |
if linux_aio is not None: |
| 155 |
extra_asyncio_variants.append(named_variant( |
| 156 |
"linux_aio[deferred=True]", |
| 157 |
AsyncioContext=functools.partial(linux_aio_asyncio.AsyncioContext, deferred=True), |
| 158 |
)) |
| 159 |
|
| 160 |
all_variants = variants + tuple(extra_context_variants) |
| 161 |
all_variants_asyncio = variants_asyncio + tuple(extra_asyncio_variants) |
| 162 |
|
| 163 |
# extra_context_variants are always linux_uring, always polling-capable - |
| 164 |
# added directly rather than via hasattr() (doesn't see through partial). |
| 165 |
polling_variants = [ |
| 166 |
v for v in variants if hasattr(v.Context, "process_events") |
| 167 |
] + extra_context_variants |
| 168 |
|
| 169 |
# Only thread_aio/python_aio have a worker-pool queue distinct from |
| 170 |
# "accepted" - max_requests/pool_size are independent there. |
| 171 |
pooled_variants = tuple(v for v in variants if v in (thread_aio, python_aio)) |
| 172 |
|
| 173 |
|
| 174 |
@pytest.fixture(params=pooled_variants) |
| 175 |
def pooled_backend(request): |
| 176 |
return request.param |
| 177 |
|
| 178 |
|
| 179 |
def drain(ctx, want, timeout=5.0): |
| 180 |
"""Waits for `want` completions via whatever polling API the backend |
| 181 |
exposes, without busy-spinning (a tight CPU-bound retry loop can starve |
| 182 |
a backend's own background thread/kernel thread of scheduling time) |
| 183 |
and without silently giving up (raises on timeout instead).""" |
| 184 |
total = 0 |
| 185 |
if hasattr(ctx, "flush"): |
| 186 |
total += ctx.flush() |
| 187 |
deadline = time.monotonic() + timeout |
| 188 |
while total < want: |
| 189 |
if time.monotonic() > deadline: |
| 190 |
raise TimeoutError(f"drain: only {total}/{want} completions after {timeout}s") |
| 191 |
time.sleep(0.001) |
| 192 |
total += ctx.process_events() |
| 193 |
return total |
| 194 |
|
| 195 |
|
| 196 |
def wait_until(ctx, predicate, timeout=5.0): |
| 197 |
"""Like drain(), but works across every backend uniformly, including |
| 198 |
the two purely callback-driven ones (thread_aio/python_aio, whose |
| 199 |
Context has no flush()/process_events() at all - results just arrive |
| 200 |
on a background worker thread on their own). Polls an arbitrary |
| 201 |
predicate (e.g. `lambda: len(results) >= n`) instead of a completion |
| 202 |
count, pumping the context each iteration only for backends that |
| 203 |
actually need pumping to make progress.""" |
| 204 |
deadline = time.monotonic() + timeout |
| 205 |
while not predicate(): |
| 206 |
if time.monotonic() > deadline: |
| 207 |
raise TimeoutError(f"condition not met within {timeout}s") |
| 208 |
if hasattr(ctx, "flush"): |
| 209 |
ctx.flush() |
| 210 |
if hasattr(ctx, "process_events"): |
| 211 |
ctx.process_events() |
| 212 |
time.sleep(0.001) |
| 213 |
return True |
| 214 |
|
| 215 |
|
| 216 |
@pytest.fixture(params=all_variants) |
| 217 |
def context_maker(request): |
| 218 |
return request.param.Context |
| 219 |
|
| 220 |
|
| 221 |
@pytest.fixture(params=all_variants) |
| 222 |
def operation_maker(request): |
| 223 |
return request.param.Operation |
| 224 |
|
| 225 |
|
| 226 |
@pytest.fixture(params=all_variants) |
| 227 |
def backend(request): |
| 228 |
# Keeps Context/Operation paired from the same backend, unlike |
| 229 |
# context_maker+operation_maker's independent cross product. |
| 230 |
return request.param |
| 231 |
|
| 232 |
|
| 233 |
@pytest.fixture(params=all_variants_asyncio) |
| 234 |
def async_context_maker(request): |
| 235 |
return request.param.AsyncioContext |
| 236 |
|
| 237 |
|
| 238 |
@pytest.fixture(params=all_variants_asyncio) |
| 239 |
async def async_context(request): |
| 240 |
"""Ready, already-entered AsyncioContext, default args. Use |
| 241 |
async_context_maker instead for a non-default constructor kwarg.""" |
| 242 |
async with request.param.AsyncioContext() as context: |
| 243 |
yield context |
| 244 |
|
| 245 |
|
| 246 |
@pytest.fixture(params=polling_variants) |
| 247 |
def polling_backend(request): |
| 248 |
return request.param |