Skip to content
Merged
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
88 changes: 88 additions & 0 deletions bindings/py/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,94 @@ def changed(sender: IObservableMap_String_Object, args: IMapChangedEventArgs_Str
unsubscribe = properties.subscribe_map_changed(changed)
```

### Async notification handlers

Use the public `AsyncEventScope` to attach an async handler to an existing
`subscribe_*` method:

```python
import asyncio
from dynwinrt import AsyncEventScope, RoApartment, projected_lifetime_scope
from generated.windows.foundation.collections import (
IMapChangedEventArgs_String, IObservableMap_String_Object, PropertySet,
)

async def on_changed(
sender: IObservableMap_String_Object, args: IMapChangedEventArgs_String,
) -> None:
await asyncio.sleep(0)
print(args.key, len(sender))

async def main() -> None:
with RoApartment(), projected_lifetime_scope():
properties = PropertySet()
async with AsyncEventScope(loop=asyncio.get_running_loop()) as events:
unsubscribe = events.subscribe(properties.subscribe_map_changed, on_changed)
properties["first"] = None
unsubscribe() # Stop future notifications; the accepted task still runs.
properties["not-delivered"] = None
# Subscriptions are removed and all accepted tasks have finished here.
# Only now may the projection scope and COM apartment close.

asyncio.run(main())
```

The [async-events sample](../../samples/python/async-events/) runs real
`PropertySet.MapChanged` notifications and native asynchronous file I/O,
including an optional handler-failure path.

`AsyncEventScope` composes `asyncio.TaskGroup`: normal exit first stops
accepting notifications and removes subscriptions, then **waits for accepted
tasks without cancelling them**. A handler failure or exception in the body
cancels siblings and waits for their `finally` blocks before propagating the
standard task-group exception; external cancellation also waits for cleanup.
A handler's own `CancelledError` has the standard TaskGroup meaning, not an
instruction to cancel all siblings. Handlers run concurrently; completion
order is not guaranteed, and there is no backpressure, throttling or retry
policy. Handlers must cooperate with cancellation.

The returned unsubscribe callable is idempotent after successful removal and
does not cancel accepted tasks. A native removal failure is raised to its
caller, leaves delivery disabled, and can be retried with the same callable
on the owner loop/thread while native owners are still live. Scope exit
attempts **every** remaining removal in reverse registration order. Removal
failures (and non-cancellation body exceptions) are preserved in an exception
group passed to TaskGroup, cancelling outstanding work rather than hanging in
a normal drain. A body's `CancelledError` is TaskGroup control flow, not an
extra leaf added to that cleanup error group. When cancellation coincides with
other errors, their propagation and cancellation bookkeeping follow the running
Python version's TaskGroup semantics. Save unsubscribe callables if your
application needs to recover from native removal failures; recovery must happen
before closing native lifetimes.

The scope is single-use and must exit in the task that entered it. Its
constructor binds it to the creating OS thread; entry, subscription, callbacks,
task execution, and unsubscription require that thread and the supplied
**actually running** loop. Keep the outer `RoApartment` and any captured
`projected_lifetime_scope()` alive through task cleanup. Existing subscription
context-variable and projection-lifetime behavior is preserved, not bypassed.
Wrong-thread delivery fails through the existing synchronous native callback
error path (`sys.unraisablehook` and a failing delegate HRESULT); the event
source decides whether that HRESULT fails the originating invocation. No
native arguments are marshalled or queued to another thread. Registration and
task-creation failures likewise remain synchronous callback/subscription errors.

This is only for ordinary same-thread notifications whose work may be deferred.
The application must drive asyncio: the scope does not create a loop, start a
thread, integrate a WinUI message pump, or make a blocking `Application.start()`
advance asyncio. It does not implement synchronous return values, `Handled`,
`Cancel`, or deferral semantics, and is not a general async adapter for WinUI
buttons or all Windows events. With an eager task factory, a handler may start
before the native callback returns, including during subscription.
Native reentrancy restrictions still apply: for example, yield before mutating
the same `PropertySet` from its handler when using an eager factory.

The handler may be an `async def` or a callable returning an awaitable; it is
called inside an owned task and its result is awaited. Passing a bare
`async def` directly to the old `subscribe_*` API instead merely creates an
unawaited coroutine. Existing synchronous callbacks, native delegates, and
synchronous callbacks returning an already TaskGroup-owned task are unchanged.

Async-operation arguments deliberately stay raw. A work item can inspect its
`IAsyncInfo` status without installing another completion handler:

Expand Down
22 changes: 21 additions & 1 deletion bindings/py/dynwinrt.pyi
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
from asyncio import AbstractEventLoop
from collections.abc import Coroutine
from datetime import datetime, timedelta
from os import PathLike
from typing import Any, Awaitable, Callable, Final, Generic, List, Literal, Mapping, Optional, Protocol, Sequence, TypeVar, Union, final, overload
from types import TracebackType
from typing import Any, Awaitable, Callable, Final, Generic, List, Literal, Mapping, Optional, ParamSpec, Protocol, Sequence, TypeVar, Union, final, overload
from uuid import UUID

_T = TypeVar("_T", covariant=True)
Expand All @@ -10,6 +12,7 @@ _Tracked = TypeVar("_Tracked")
_Projected_co = TypeVar("_Projected_co", covariant=True)
_ProjectableClass = TypeVar("_ProjectableClass", bound="_DynWinRTProjectableClass")
_Handlers_contra = TypeVar("_Handlers_contra", contravariant=True)
_EventArgs = ParamSpec("_EventArgs")


class _DynWinRTProjector(Protocol[_Projected_co]):
Expand All @@ -24,6 +27,7 @@ class _DynWinRTRuntimeClass(_DynWinRTProjectableClass): ...


__all__ = [
"AsyncEventScope",
"WinAppSDKContext",
"RoApartment",
"RO_INIT_SINGLETHREADED",
Expand Down Expand Up @@ -66,6 +70,22 @@ __all__ = [
"get_computer_name",
]

@final
class AsyncEventScope:
def __init__(self, *, loop: AbstractEventLoop) -> None: ...
async def __aenter__(self) -> AsyncEventScope: ...
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc_value: BaseException | None,
traceback: TracebackType | None,
) -> None: ...
def subscribe(
self,
subscribe: Callable[[Callable[_EventArgs, object]], Callable[[], None]],
handler: Callable[_EventArgs, Awaitable[object]],
) -> Callable[[], None]: ...

@final
class WinAppSDKContext:
def resource_pri_path(self) -> str: ...
Expand Down
3 changes: 2 additions & 1 deletion bindings/py/python/dynwinrt/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
from . import dynwinrt as dynwinrt
from .dynwinrt import *
from . import values as values
from ._events import AsyncEventScope as AsyncEventScope
from ._winappsdk import init_winappsdk as init_winappsdk

__doc__ = dynwinrt.__doc__
__all__ = dynwinrt.__all__
__all__ = [*dynwinrt.__all__, "AsyncEventScope"]
138 changes: 138 additions & 0 deletions bindings/py/python/dynwinrt/_events.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.

"""Structured concurrency for same-thread, asynchronous notification handlers."""

from __future__ import annotations

import asyncio as _asyncio
import threading as _threading
from collections.abc import Awaitable as _Awaitable, Callable as _Callable
from types import TracebackType as _TracebackType
from typing import ParamSpec as _ParamSpec, final as _final

_Args = _ParamSpec("_Args")


@_final
class AsyncEventScope:
"""Own notification subscriptions and their concurrent TaskGroup tasks.

The application must drive ``loop`` on the creating OS thread and keep its
COM apartment and projected lifetimes alive until this context has exited.
Only ordinary notifications that may be handled later are supported.
"""

def __init__(self, *, loop: _asyncio.AbstractEventLoop) -> None:
self._loop = loop
self._thread = _threading.current_thread()
self._group = _asyncio.TaskGroup()
self._state = "new"
self._owner_task: _asyncio.Task[object] | None = None
self._subscriptions: list[_Callable[[], None]] = []

def _check_owner(self) -> None:
if _threading.current_thread() is not self._thread:
raise RuntimeError("AsyncEventScope requires its owner OS thread")
if _asyncio.get_running_loop() is not self._loop:
raise RuntimeError("AsyncEventScope requires its running asyncio loop")

async def __aenter__(self) -> AsyncEventScope:
self._check_owner()
if self._state != "new":
raise RuntimeError("AsyncEventScope cannot be re-entered or reused")
await self._group.__aenter__()
self._owner_task = _asyncio.current_task()
self._state = "active"
return self

def subscribe(
self,
subscribe: _Callable[[_Callable[_Args, object]], _Callable[[], None]],
handler: _Callable[_Args, _Awaitable[object]],
) -> _Callable[[], None]:
"""Register a handler; return a retryable, idempotent unsubscribe.

Unsubscribing stops new deliveries before attempting native removal.
Already accepted tasks remain owned by the scope, even if removal fails.
The handler is called inside a group task and its result is awaited.
"""
self._check_owner()
if self._state != "active":
raise RuntimeError("AsyncEventScope is not accepting subscriptions")
if not callable(subscribe) or not callable(handler):
raise TypeError("subscribe and handler must be callable")
accepting = True
removing = False
remove: _Callable[[], None] | None = None

async def invoke(*args: _Args.args, **kwargs: _Args.kwargs) -> None:
self._check_owner()
await handler(*args, **kwargs)

def callback(*args: _Args.args, **kwargs: _Args.kwargs) -> None:
self._check_owner()
if not accepting or self._state != "active":
return
coroutine = invoke(*args, **kwargs)
try:
self._group.create_task(coroutine)
except BaseException:
# TaskGroup only closes rejected coroutines on Python 3.13+.
coroutine.close()
raise

def unsubscribe() -> None:
nonlocal accepting, removing, remove
self._check_owner()
accepting = False
if remove is None or removing:
return
removing = True
try:
remove()
remove = None
self._subscriptions.remove(unsubscribe)
finally:
removing = False

try:
remove = subscribe(callback)
if not callable(remove):
raise TypeError("subscribe must return an unsubscribe callable")
except BaseException:
accepting = False
raise
self._subscriptions.append(unsubscribe)
return unsubscribe

async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc_value: BaseException | None,
traceback: _TracebackType | None,
) -> None:
self._check_owner()
if self._state != "active":
raise RuntimeError("AsyncEventScope is not active")
if _asyncio.current_task() is not self._owner_task:
raise RuntimeError("AsyncEventScope must exit in the task that entered it")
self._state = "closing"
errors: list[BaseException] = []
for unsubscribe in reversed(self._subscriptions.copy()):
try:
unsubscribe()
except BaseException as error:
errors.append(error)
if errors:
# TaskGroup handles cancellation separately from ordinary errors.
if exc_value is not None and not isinstance(exc_value, _asyncio.CancelledError):
errors.insert(0, exc_value)
exc_value = BaseExceptionGroup("AsyncEventScope unsubscribe failed", errors)
exc_type = type(exc_value)
traceback = exc_value.__traceback__
try:
await self._group.__aexit__(exc_type, exc_value, traceback)
finally:
self._state = "closed"
self._owner_task = None
Loading
Loading