Add asyncio support - #359
Conversation
fix typo
Handle timeout in aread_response
Merge from upstream
* Comment annotation fixups * Added SdoServer aupload and adownload * Fix missing Network.is_async() uses * Fix workaround in pdo.map.save/asave
|
What is the best way to deal with var = param.data # Non-async use
var = await param.aget_data() # Async useMy goal has been to keep the async and non-async uses of canopen as equal as possible, but this is an area where users will see a difference. |
|
There is an implementation for |
|
@acolomb I'm not precisely sure what you mean, so let me guess: You need separate |
|
Sorry, I was trying to answer your question in the previous comment about synchronous getters / setters used in the properties. What I meant was that instead we already do have methods to access a variable remotely. Those might be a better fit to mirror to the async world: value = sdo_var.raw # This is the usual, terse style recommended in the docs
value = sdo_var.read(fmt='raw') # This also works already
value = await sdo_var.aread(fmt='raw') # Feels like a natural enhancement for asyncNote that the |
* Thread dependent sentinel guard
* All callbacks are synchronous and same in both sync and async mode * Sync waiting is done with `asyncio.to_thread()` from async
Codecov ReportAttention: Patch coverage is
📢 Thoughts on this report? Let us know! |
* Make code more similar the upstream code * Implement missing async functions * Update README.rst and example * Revert test cases to be diffable with upstream * Ensure all skipTest() have useful messages * Wash FIXMEs and NOTEs
* Adding `AllowBlocking` for temporary pausing the async guard * skipTest() cleanup * Increase test coverage
* OD object lookup issue * SDO testing warning issue
* Fixed uncovered bugs * Bumped minimum py version to 3.9 (due to asyncio compatibility) * Added tests for PDO to increase coverage
|
This branch is ready for review and integration into the project. Its not fully complete (I suppose it never will). The biggest lack is that there is no documentation for async. The branch's README (https://github.com/sveinse/canopen-asyncio?tab=readme-ov-file#difference-between-async-and-non-async-version) contains an overview over the current differences between this branch and the main project. The port is quite "naive" async-wise as it relies on |
acolomb
left a comment
There was a problem hiding this comment.
Phew, that's a lot of material and I hope you don't mind my elaborate review comments. But first, let's take a step back and see if we can better define what the PR does and what the goals are.
I'm not really experienced with asyncio based programming in Python, but I do know pretty well what an event loop and coroutines are. So my main mental challenge with this is trying to imagine what an application would really look like if using asyncio to handle its functionality elegantly. From own experience, I'd say moving long-blocking background activities from threads to a (cooperatively scheduled) task is one of the main motivations -- such as waiting for a drive homing procedure to finish.
My impression on what this focuses on, with some overall remarks about the implementation:
-
Finding and marking all API functions potentially blocking on I/O. This is a useful thing in itself, but I don't think we want the NOTE comments in the code indefinitely. It makes sense to gather findings like you did now, but provides little extra value to the library consumer and will bit-rot really fast I suppose.
-
Detecting improper use of blocking functions in async context, which would block the main loop. This is useful but totally optional IMHO, so could better be moved to its own PR to focus on the actual async capabilities first. An approach with a single
assert canopen.async_guard.ensure_not_asyncline (or similar) could be just as good as the decorator approach, but clearer. -
Arranging user callbacks to be scheduled in the event loop instead of called immediately. I see several alternatives to the current dispatcher solution, so let's clarify what situation this applies to: A CAN message arrives on the network and the application needs to passively react to this external trigger. The reaction may be an internal callback (as in p402.py) or an arbitrarily long-running external application function. This uncertainty must be contained to not block the main event loop. Traditionally, it is executed inside the RX thread of python-can's
Notifieranyway, blocking that at worst. There is already functionality in there to schedule callbacks as tasks if they are coroutines, execute directly otherwise. So the easiest would be for the application to provide a coroutine directly as callback -- this just needs to be passed through the canopen library, so that the listener is also an async / await wrapper around the application callback. But shouldn't it be an application responsibility to decide whether the callback happens inside the RX background thread, or as a task on the event loop? -
Provide async (coroutine) variants of common blocking operation methods. This is the core of the "async integration" API-wise. But it's actually much less of a concern than the callback handling. Because the caller can always just do as you did in many places, calling
await asyncio.to_thread()on the existing synchronous function. Some of the really interesting functions are not converted to async variants yet. I suppose thatto_thread()approach is a stop-gap solution before implementing real, awaitable internal methods. -
Add unit tests for the new API. This is probably the largest portion of the diff, but I haven't checked it thoroughly as these high-level review points must be discussed and solved first.
Sorry if I missed something now, or it's just my lack of understanding asyncio in general. Plus I get too tired when tackling such a complex and large review late at night. But that's already lots of food for discussion I suppose.
| NOTIFIER_SHUTDOWN_TIMEOUT: float = 5.0 #: Maximum waiting time to stop notifiers. | ||
|
|
||
| def __init__(self, bus: Optional[can.BusABC] = None): | ||
| # NOTE: Function arguments changed to provide notifier, see #556 |
There was a problem hiding this comment.
As discussed in #556, this can simply be set between __init__() and connect(), with the latter only creating one if not already set (as you did).
There was a problem hiding this comment.
Yes, that should be possible. Why the reluctance to add to the signature of __init__() thou? It is not altering any existing behavior.
I personally find the first more elegant that the latter:
# Easy
network = Network(bus=bus, notifier=mynotifier)
# More clunky
network = Network(bus=bus)
network.notifier = mynotifer| logger.error("An error has caused receiving of messages to stop") | ||
| raise exc | ||
|
|
||
| def is_async(self) -> bool: |
There was a problem hiding this comment.
Fixed. I'm curious: What makes you want this to be a property? What's wrong with a method?
| # Exceptions in any callbaks should not affect CAN processing | ||
| logger.exception("Exception in callback: %s", exc_info=exc) | ||
|
|
||
| def dispatch_callbacks(self, callbacks: List[Callback], *args) -> None: |
There was a problem hiding this comment.
This is one of the central elements it seems, making it easy to influence what exactly "invoking a callback" means and does. The approach is alright and the Network seems like a good place to handle such a definition centrally.
However, I'm unsure whether this is the best / only solution regarding callbacks. One alternative that springs to mind is to wrap each given callback function when it is registered somewhere, replacing it with a callable that creates the corresponding task instead of executing the given callback directly.
There was a problem hiding this comment.
I'm not sure what you precisely mean by the first comment, but the term "callback" is consistently used for any function that that handles incoming CAN messages via the notification & listener system from python-can.
The reason for adding def dispatch_callbacks() is that coroutine callbacks needs special steps to be called. In order to run a coroutine a task be created and the future object must be kept so the GC doesn't delete the object before ever running the callback.
| * The mechanism for CAN bus callbacks have been changed. Callbacks might be | ||
| async, which means they cannot be called immediately. This affects how | ||
| error handling is done in the library. |
There was a problem hiding this comment.
This sounds a lot like duplicating what python-can already provides. Can we embrace that lower-level concept more instead of building our own dispatcher?
There was a problem hiding this comment.
Yes we can. It does require a refactor of the callback system if we want that. See the main comment for more.
| """ | ||
| return self._node.get_data(index, subindex) | ||
|
|
||
| async def aupload(self, index: int, subindex: int) -> bytes: |
There was a problem hiding this comment.
Since there is no blocking access, we don't really need the async method variants on the SdoServer (nor SdoBase for that matter). Unless LocalNode.get_data() is also allowed to be a blocking access pattern, implemented as a coroutine itself, there is no value in wrapping it here like this. The only expected blocking I/O on the library side is the SdoClient, thus the async methods can be introduced only there.
There was a problem hiding this comment.
The idea I've attempted to be consistent about is that the async API should mirror the regular API (that's what you'd expect from an async API, right?). The SdoServer.aupload() implementation happen to be equal to SdoServer.upload() and could be removed. On the other hand SdoClient.aupload() is not equal to SdoClient.upload(). It happens to be that way because of how we've implemented SdoServer. Should the user need to know that when using it? If we do remove SdoServer.aupload() the user will have to change its implementation if SdoServer.upload() becomes blocking and we then need SdoServer.aupload().
| def read_generator(self): | ||
| """Generator to run through steps for reading the PDO configuration |
There was a problem hiding this comment.
I like this solution. Maybe a similar pattern can be applied in other places?
There was a problem hiding this comment.
Yes, this concept is called sansio. This is what we need to make the SDO protocol handlers and all the other completely independent of what IO type (blocking vs async) is used. Basically its a system to put data in -> get something to send. Rinse and repeat until done.
|
Thank you for reviewing them @acolomb. You certainly did a thorough job! I'm currently on a sick leave, so I don't think I'll get any change to look at them immediately thou. This is what I propose as next steps:
Regarding the "NOTE" and "Blocking call". These are markers I put in the after doing an investigation of what breaks. As we've been discussing before, this library does a lot of blocking IO in unconventional calls, such as in properties, so it took some efforts to find them all. My intentions is to remove these markers before the final merge. |
|
Again, thank you @acolomb for the detailed review. This is a lengthy reponse, with this comment and the answers to the code comments. I've update the PR to align with the current master and I've made cleanups and some fixes. I hope you'll find the PR less cluttered now. I recognize that this PR is huge and it contains many different elements. Should we maybe split this PR into multiple parts? There is an elephant in the room: Is getting this adopted into canopen the way everyone wants it is too much effort? Perhaps the need for having async support isn't that big. This can live side by side. GoalThe overall goal for this initiative is to add async support to canopen. With it the user shall be able to decide if the canopen library should be used with regular blocking calls or using asyncio. With async the user will be able to invoke many concurrent requests without needing to revert to threads. Challenges
In useI'd like to mention that the asyncio port isn't untested. At work we use Answers to key questions
Let's do this in a separate PR. When apps are done right, these guards aren't really needed. But this protection has proven to be most useful, especially when working on async vs non-async development. An incorrect blocking IO call is easy to do by mistake and finding them without the guard can be very challenging. Which of these two approaches do you think is most clean? I assume you prefer alternative 2? # Alternative 1
@ensure_not_async
def something_to_protect():
...
# Alternative 2
def something_to_protect():
assert canopen.async_guard.ensure_not_async()
...
This is a key question and it has huge impact on the overall design. There are indeed several ways of doing it. It is correct that python-can have a mechanism for calling coroutines on rx of CAN messages. If the callback, i.e. However, all incoming messages are wrapped via There is a way around this if each callback in canopen implements a
The whole back-end listener / notification system is based on regular functions which are called immediately in the rx thread. Any user provided non-async callbacks will also be executed in the rx thread. In both async and non-async mode currently. Any coroutine callbacks, will always be executed in the event loop thread.
Yes, We currently need this internally because of the way the back-end listener / notification system is built and the usage of blocking locking primitives. We could completely avoid
Choosing test strategy was a choice between a rock and a hard place when making the test setup. There are (at least) two options for a dual-stack setup like this:
So far I've chosen the latter and the first easily makes the async and non-aync drift a part. But I'm not liking the implications the dual mode tests. It makes the unit tests very clunky and very hard to update. |
This PR adds support of asyncio to canopen. The overall goals is to make canopen able to be used in either with asyncio or regular synchronous mode (but not at the same time) from the same code base.
Note that this work is still work in progress. This PR was created to discuss the specific solutions for async and non-async as mentioned in #272. This PR closes #272.
Current status until feature complete:
ImplementNot neededABlockUploadStream,ABlockDownloadStreamandATextIOWrapperfor async inSdoClient.EcmyConsumer.wait()for asyncAsync implementation ofOnlyLssMasterfast_scanBaseNode402~Omitted for nowNetwork.add_node()