Skip to content

Request: async methods on ServiceListener #1075

Closed as not planned
Closed as not planned

Description

@dge8

Hello,

I've started using python-zeroconf in an async project, and would like to ask whether it could be made possible for the ServiceListener callbacks (add_service, update_service and remove_service) to be async coroutines instead of sync functions.

To illustrate I've rewritten the service browser example in the Readme using async methods. Note that async_add_service_listener() along with async with really tidy up the main loop, but the sync-async friction makes the ServiceListener a bit messy (plus need to handle the AsyncZeroconf object separately).

(A related question linked to this example: which thread executes the ServiceListener callbacks? Should I be using asyncio.create_task() or asyncio.run_coroutine_threadsafe()?)

Async MWE of service browser in readme
import asyncio, sys
from zeroconf import ServiceListener, Zeroconf
from zeroconf.asyncio import AsyncZeroconf

SERVICE_TYPE = "_http._tcp.local."

class MyListener(ServiceListener):

    def __init__(self, aiozc: AsyncZeroconf):
        self.aiozc = aiozc

    def update_service(self, zc: Zeroconf, type_: str, name: str) -> None:
        print(f"Service {name} updated")

    def remove_service(self, zc: Zeroconf, type_: str, name: str) -> None:
        print(f"Service {name} removed")

    def add_service(self, zc: Zeroconf, type_: str, name: str) -> None:
        # Should this be asyncio.run_coroutine_threadsafe() for thread safety?
        asyncio.create_task(self.async_add_service(zc, type_, name))

    async def async_add_service(self, zc: Zeroconf, type_: str, name: str) -> None:
        info = await self.aiozc.async_get_service_info(type_, name)
        print(f"Service {name} added, service info: {info}")

async def get_all_services():
    async with AsyncZeroconf() as aiozc:
        listener = MyListener(aiozc)
        await aiozc.async_add_service_listener(SERVICE_TYPE, listener)
        while True:
            await asyncio.sleep(10)

try:
    print("Press Ctrl-C to exit...\n")
    asyncio.run(get_all_services())
except KeyboardInterrupt:
    sys.exit()

It would be much nicer to be able to do the following instead, perhaps via an AsyncServiceListener class:

class MyAsyncListener(AsyncServiceListener):

    async def async_update_service(self, aiozc: AsyncZeroconf, type_: str, name: str) -> None:
        print(f"Service {name} updated")

    async def async_remove_service(self, aiozc: AsyncZeroconf, type_: str, name: str) -> None:
        print(f"Service {name} removed")

    async def async_add_service(self, aiozc: AsyncZeroconf, type_: str, name: str) -> None:
        info = await aiozc.async_get_service_info(type_, name)
        print(f"Service {name} added, service info: {info}")

async def get_all_services():
    async with AsyncZeroconf() as aiozc:
        listener = MyAsyncListener()
        await aiozc.async_add_service_listener(SERVICE_TYPE, listener)
        while True:
            await asyncio.sleep(10)

What do others think? Is there a better way to achieve what I'm after?

Thanks,
Dan.

P.S. Thank you to everyone who's put time into this project!

Activity

  1. bdraco commented on Jun 14, 2022

    @bdraco
    Member

    asyncio.create_task is a good solution for what you need (most of the examples use asyncio.ensure_future for compat with older python). Coroutines are much slower than running a callback function so we would not want to make them coroutines by default since these can fire quite frequently. If we supported both we would still have to check if its a callback or coroutine each time it was about to be executed which is a non-trivial check and could add up quickly on a busy network.

  2. dge8 commented on Jun 16, 2022

    @dge8
    Author

    Thanks @bdraco - would performance be acceptable if the check was done just once when registering the listener object and stored in a flag? Or instead of checking whether each method is a function or a coroutine, check if the listener is a Listener or AsyncListener object?

    Also, you've suggested asyncio.create_task, can you confirm that the callbacks will always be executed from the same thread as the asyncio event loop?

    Thanks again,
    Dan.

  3. bdraco commented on Jun 16, 2022

    @bdraco
    Member

    Thanks @bdraco - would performance be acceptable if the check was done just once when registering the listener object and stored in a flag? Or instead of checking whether each method is a function or a coroutine, check if the listener is a Listener or AsyncListener object?

    That's the usual way to solve the performance issue. Every project we have done this on we regretted doing it later since it adds quite a bit of maintenance future burden when we need to change things later. We are currently facing a performance problem with an ssdp library that Home Assistant uses for this reason. I would prefer not to go down this road.

    Also, you've suggested asyncio.create_task, can you confirm that the callbacks will always be executed from the same thread as the asyncio event loop?

    Yes it calls get_running_loop under the hood

    Thanks again,

    Dan.

  4. dge8 commented on Jun 19, 2022

    @dge8
    Author

    Thanks, I think I understand. I was confused by the docstring for AsyncZeroconf which says "The async version is currently a wrapper around the sync version with I/O being done in the executor for backwards compatibility", which I interpreted to mean that the callbacks would also be called from within the executor and therefore from a different thread. Not the case then.

    Since the callbacks are synchronous and called from the main thread when using AsyncZeroconf, I assume it's also safe to maintain a list/cache of services like this?

    class MyListener(ServiceListener):
    
        def __init__(self):
            self.services = []
    
        def add_service(self, zc: Zeroconf, type_: str, name: str) -> None:
            if name not in self.services:
                self.services.append(name)
    
        def update_service(self, zc: Zeroconf, type_: str, name: str) -> None:
            if name not in self.services:
                self.services.append(name)
    
        def remove_service(self, zc: Zeroconf, type_: str, name: str) -> None:
            if name in self.services:
                self.services.remove(name)

    Thanks,
    Dan.

  5. bdraco commented on Jun 19, 2022

    @bdraco
    Member

    That docstring is stale from when we were transitioning to asyncio. I'll get that updated.

    As long as you start the instance from the event loop or use AsyncZeroconf, everything will run in the same thread so there isn't a need to worry about thread safety.

    If you don't have a running event loop, and use Zeroconf, everything starts in a separate thread in its own event loop.

    The short/naïve answer to your question is : it is probably safe assuming there isn't anything else causing it to be called in another thread outside of zeroconf

  6. dge8 commented on Jun 19, 2022

    @dge8
    Author

    Great, that clears things up, thanks again @bdraco. Will close the issue (as not planned, if that's ok, since the primary issue was async methods on ServiceListener/an AsyncServiceListener).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions