AsyncManager Class¶
cymongoose.AsyncManager
¶
Asyncio-compatible wrapper around Manager.
Runs the mongoose event loop in a daemon thread. poll() releases
the GIL, so the asyncio event loop runs concurrently without blocking.
The thread-safe wakeup() method enables asyncio -> mongoose
communication.
Usage::
async with AsyncManager(handler) as am:
am.listen("http://0.0.0.0:8080")
# ... do async work ...
Source code in src/cymongoose/aio.py
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 | |
_handler = handler
instance-attribute
¶
_poll_interval = poll_interval
instance-attribute
¶
_error_handler = error_handler
instance-attribute
¶
_shutdown_timeout = shutdown_timeout
instance-attribute
¶
_manager = None
instance-attribute
¶
_thread = None
instance-attribute
¶
_stop = threading.Event()
instance-attribute
¶
_lock = threading.RLock()
instance-attribute
¶
_loop = None
instance-attribute
¶
_wake_id = 0
instance-attribute
¶
_MAX_POLL_MS = 200
class-attribute
instance-attribute
¶
manager
property
¶
Access the underlying Manager.
running
property
¶
__init__(handler=None, poll_interval=100, error_handler=None, shutdown_timeout=30)
¶
Create an AsyncManager.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
handler
|
Optional[Callable[..., Any]]
|
Default event handler for all connections. |
None
|
poll_interval
|
int
|
Milliseconds between poll() calls (default 100). |
100
|
error_handler
|
Optional[Callable[[Exception], Any]]
|
Called when a handler raises an exception. |
None
|
shutdown_timeout
|
float
|
Hard limit in seconds for
The warnings surface in logs so operators can identify
blocked handlers. Retrying the wakeup at each interval
guards against a lost initial wakeup that raced with the
handler entering |
30
|
Source code in src/cymongoose/aio.py
__aenter__()
async
¶
Source code in src/cymongoose/aio.py
__aexit__(*exc)
async
¶
Source code in src/cymongoose/aio.py
_run()
¶
Source code in src/cymongoose/aio.py
_wake_poll()
¶
Best-effort interrupt of poll() to reduce lock acquisition latency.
Writes to the wakeup pipe so select()/epoll_wait() returns
immediately, causing poll() to release the lock sooner.
Source code in src/cymongoose/aio.py
_track_conn(conn)
¶
listen(url, handler=None, *, http=None)
¶
Source code in src/cymongoose/aio.py
connect(url, handler=None, *, http=None)
¶
Source code in src/cymongoose/aio.py
mqtt_connect(url, **kwargs)
¶
Source code in src/cymongoose/aio.py
mqtt_listen(url, handler=None)
¶
Source code in src/cymongoose/aio.py
sntp_connect(url, handler=None)
¶
Source code in src/cymongoose/aio.py
wakeup(connection_id, data=b'')
¶
Thread-safe: wakeup does not need the lock.
timer_add(ms, callback, *, repeat=False, run_now=False)
¶
Source code in src/cymongoose/aio.py
schedule(coro_or_callback)
¶
Schedule a coroutine or callback on the asyncio event loop.
This is thread-safe and intended to be called from the mongoose poll thread (i.e. from inside event handlers) to push work back onto the asyncio loop.
Source code in src/cymongoose/aio.py
Overview¶
AsyncManager wraps Manager for use with Python's asyncio. It runs the
mongoose event loop in a daemon thread while the asyncio event loop runs
concurrently. Since poll() releases the GIL, both loops make progress
without blocking each other.
Basic Usage¶
import asyncio
from cymongoose import AsyncManager, MG_EV_HTTP_MSG
def handler(conn, ev, data):
if ev == MG_EV_HTTP_MSG:
conn.reply(200, b"Hello from async!")
async def main():
async with AsyncManager(handler) as am:
am.listen("http://0.0.0.0:8080")
# Server is running -- do async work here
await asyncio.sleep(60)
asyncio.run(main())
Constructor¶
cymongoose.AsyncManager.__init__(handler=None, poll_interval=100, error_handler=None, shutdown_timeout=30)
¶
Create an AsyncManager.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
handler
|
Optional[Callable[..., Any]]
|
Default event handler for all connections. |
None
|
poll_interval
|
int
|
Milliseconds between poll() calls (default 100). |
100
|
error_handler
|
Optional[Callable[[Exception], Any]]
|
Called when a handler raises an exception. |
None
|
shutdown_timeout
|
float
|
Hard limit in seconds for
The warnings surface in logs so operators can identify
blocked handlers. Retrying the wakeup at each interval
guards against a lost initial wakeup that raced with the
handler entering |
30
|
Source code in src/cymongoose/aio.py
Parameters¶
| Parameter | Type | Default | Description |
|---|---|---|---|
handler |
Callable or None |
None |
Default event handler (conn, ev, data) -> None |
poll_interval |
int |
100 |
Milliseconds between poll() calls |
error_handler |
Callable or None |
None |
Called with (exc: Exception) when a handler raises |
shutdown_timeout |
float |
30 |
Seconds to wait for the poll thread on exit |
Listening for Connections¶
async with AsyncManager(handler) as am:
# HTTP server
am.listen("http://0.0.0.0:8080")
# With per-listener handler
am.listen("http://0.0.0.0:9090", handler=api_handler)
# MQTT broker
am.mqtt_listen("mqtt://0.0.0.0:1883")
Methods¶
cymongoose.AsyncManager.listen(url, handler=None, *, http=None)
¶
Source code in src/cymongoose/aio.py
cymongoose.AsyncManager.mqtt_listen(url, handler=None)
¶
Source code in src/cymongoose/aio.py
Making Connections¶
async with AsyncManager(handler) as am:
# HTTP client
am.connect("http://example.com:80", handler=client_handler)
# MQTT client
am.mqtt_connect("mqtt://broker.com:1883", clean_session=True)
# SNTP client
am.sntp_connect("udp://time.google.com:123", handler=time_handler)
Methods¶
cymongoose.AsyncManager.connect(url, handler=None, *, http=None)
¶
Source code in src/cymongoose/aio.py
cymongoose.AsyncManager.mqtt_connect(url, **kwargs)
¶
Source code in src/cymongoose/aio.py
cymongoose.AsyncManager.sntp_connect(url, handler=None)
¶
Source code in src/cymongoose/aio.py
Timers¶
async with AsyncManager() as am:
# One-shot timer
am.timer_add(5000, lambda: print("fired"))
# Repeating timer
timer = am.timer_add(1000, heartbeat, repeat=True)
# ...
timer.cancel()
cymongoose.AsyncManager.timer_add(ms, callback, *, repeat=False, run_now=False)
¶
Source code in src/cymongoose/aio.py
Thread-Safe Communication¶
Wakeup¶
wakeup() is thread-safe and does not require the internal lock:
async with AsyncManager(handler, enable_wakeup=True) as am:
listener = am.listen("http://0.0.0.0:8080")
# From any thread or coroutine:
am.wakeup(conn_id, b"data")
cymongoose.AsyncManager.wakeup(connection_id, data=b'')
¶
Thread-safe: wakeup does not need the lock.
Scheduling Asyncio Work from Handlers¶
Use schedule() to push work from the mongoose poll thread back onto
the asyncio event loop:
async def process_request(data):
result = await some_async_operation(data)
print(f"Processed: {result}")
def handler(conn, ev, data):
if ev == MG_EV_HTTP_MSG:
conn.reply(200, b"Accepted")
# Schedule async work from the handler (runs on poll thread)
am.schedule(process_request(data.body_text))
async with AsyncManager(handler) as am:
am.listen("http://0.0.0.0:8080")
await asyncio.sleep(3600)
cymongoose.AsyncManager.schedule(coro_or_callback)
¶
Schedule a coroutine or callback on the asyncio event loop.
This is thread-safe and intended to be called from the mongoose poll thread (i.e. from inside event handlers) to push work back onto the asyncio loop.
Source code in src/cymongoose/aio.py
Properties¶
cymongoose.AsyncManager.manager
property
¶
Access the underlying Manager.
cymongoose.AsyncManager.running
property
¶
Shutdown Behavior¶
When the async with block exits, __aexit__ shuts down the poll thread:
- Signals the thread to stop and sends a wakeup.
- Waits 5 seconds for the thread to join.
- If still alive: emits a
RuntimeWarning, retries the wakeup, waits another 5 seconds. - Repeats step 3 until
shutdown_timeoutis reached. - At the hard limit: emits a final warning and moves on without calling
Manager.close().
# Tune the timeout for your application
async with AsyncManager(handler, shutdown_timeout=10) as am:
am.listen("http://0.0.0.0:8080")
# ...
# __aexit__ handles shutdown automatically
If the poll thread exits cleanly, Manager.close() is called and all
resources are freed. If the thread is abandoned (handler blocked beyond
the timeout), the daemon thread dies at process exit.
See Graceful Shutdown for more patterns.
Differences from Manager¶
| Feature | Manager |
AsyncManager |
|---|---|---|
| Event loop | Manual poll() calls |
Automatic in daemon thread |
| Concurrency | Single-threaded or manual threading | Runs alongside asyncio |
| Shutdown | Explicit close() |
Automatic via __aexit__ |
| Thread safety | poll() not reentrant |
Serialised by internal RLock |
| Wakeup | Opt-in via enable_wakeup=True |
Always enabled |
See Also¶
- Manager -- the underlying synchronous API
- Threading -- thread-safety model
- Graceful Shutdown -- shutdown patterns