Skip to content

Commit

Permalink
Remove deprecated asyncio usages
Browse files Browse the repository at this point in the history
  • Loading branch information
linuxdaemon committed Mar 15, 2024
1 parent d53b8dc commit ee2f7ab
Show file tree
Hide file tree
Showing 10 changed files with 19 additions and 53 deletions.
4 changes: 2 additions & 2 deletions cloudbot/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from cloudbot.hook import Action
from cloudbot.plugin import PluginManager
from cloudbot.reloader import ConfigReloader, PluginReloader
from cloudbot.util import async_util, database, formatting
from cloudbot.util import database, formatting
from cloudbot.util.mapping import KeyFoldDict

logger = logging.getLogger("cloudbot")
Expand Down Expand Up @@ -108,7 +108,7 @@ def __init__(
self.running = True
self.clients: Dict[str, Type[Client]] = {}
# future which will be called when the bot stopsIf you
self.stopped_future = async_util.create_future(self.loop)
self.stopped_future = self.loop.create_future()

# stores each bot server connection
self.connections = KeyFoldDict()
Expand Down
3 changes: 1 addition & 2 deletions cloudbot/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from typing import Any, Dict

from cloudbot.permissions import PermissionManager
from cloudbot.util import async_util

logger = logging.getLogger("cloudbot")

Expand Down Expand Up @@ -66,7 +65,7 @@ def __init__(self, bot, _type, name, nick, *, channels=None, config=None):

self._active = False

self.cancelled_future = async_util.create_future(self.loop)
self.cancelled_future = self.loop.create_future()

def describe_server(self):
raise NotImplementedError
Expand Down
10 changes: 5 additions & 5 deletions cloudbot/clients/irc.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

from cloudbot.client import Client, ClientConnectError, client
from cloudbot.event import Event, EventType, IrcOutEvent
from cloudbot.util import async_util, colors
from cloudbot.util import colors

logger = logging.getLogger("cloudbot")

Expand Down Expand Up @@ -391,7 +391,7 @@ def _send(self, line, log=True):
"""
Sends a raw IRC line unchecked. Doesn't do connected check, and is *not* threadsafe
"""
async_util.wrap_future(
asyncio.ensure_future(
self._protocol.send(line, log=log), loop=self.loop
)

Expand Down Expand Up @@ -423,7 +423,7 @@ def __init__(self, conn):
self._transport = None

# Future that waits until we are connected
self._connected_future = async_util.create_future(self.loop)
self._connected_future = self.loop.create_future()

def connection_made(self, transport):
self._transport = transport
Expand All @@ -438,7 +438,7 @@ def connection_lost(self, exc):
if exc:
logger.error("[%s] Connection lost: %s", self.conn.name, exc)

async_util.wrap_future(self.conn.auto_reconnect(), loop=self.loop)
asyncio.ensure_future(self.conn.auto_reconnect(), loop=self.loop)

def close(self):
self._connecting = False
Expand Down Expand Up @@ -522,7 +522,7 @@ def data_received(self, data):
)
else:
# handle the message, async
async_util.wrap_future(self.bot.process(event), loop=self.loop)
asyncio.ensure_future(self.bot.process(event), loop=self.loop)

def parse_line(self, line: str) -> Event:
message = Message.parse(line)
Expand Down
8 changes: 4 additions & 4 deletions cloudbot/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
SieveHook,
hook_name_to_plugin,
)
from cloudbot.util import HOOK_ATTR, LOADED_ATTR, async_util, database
from cloudbot.util import HOOK_ATTR, LOADED_ATTR, database
from cloudbot.util.func_utils import call_with_args

logger = logging.getLogger("cloudbot")
Expand Down Expand Up @@ -310,7 +310,7 @@ async def load_plugin(self, path):
self._log_hook(on_cap_ack_hook)

for periodic_hook in plugin.hooks["periodic"]:
task = async_util.wrap_future(self._start_periodic(periodic_hook))
task = asyncio.ensure_future(self._start_periodic(periodic_hook))
plugin.tasks.append(task)
self._log_hook(periodic_hook)

Expand Down Expand Up @@ -566,7 +566,7 @@ async def internal_launch(self, hook, event):
else:
coro = self._execute_hook_sync(hook, event)

task = async_util.wrap_future(coro)
task = asyncio.ensure_future(coro)
hook.plugin.tasks.append(task)
try:
out = await task
Expand Down Expand Up @@ -621,7 +621,7 @@ async def _sieve(self, sieve, event, hook):
coro = sieve.function(self.bot, event, hook)

result, error = None, None
task = async_util.wrap_future(coro)
task = asyncio.ensure_future(coro)
sieve.plugin.tasks.append(task)
try:
result = await task
Expand Down
29 changes: 0 additions & 29 deletions cloudbot/util/async_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,10 @@
"""

import asyncio
from asyncio import AbstractEventLoop
from asyncio.tasks import Task
from functools import partial
from typing import List, Optional, cast

from cloudbot.util.func_utils import call_with_args

try:
_asyncio_get_tasks = getattr(asyncio, "all_tasks")
except AttributeError:
_asyncio_get_tasks = getattr(Task, "all_tasks")


def wrap_future(fut, *, loop=None):
"""
Wraps asyncio.ensure_future()
:param fut: The awaitable, future, or coroutine to wrap
:param loop: The loop to run in
:return: The wrapped future
"""
return asyncio.ensure_future(fut, loop=loop)


async def run_func(loop, func, *args, **kwargs):
part = partial(func, *args, **kwargs)
Expand Down Expand Up @@ -56,14 +38,3 @@ def run_coroutine_threadsafe(coro, loop):
raise TypeError("A coroutine object is required")

asyncio.run_coroutine_threadsafe(coro, loop)


def create_future(loop):
return loop.create_future()


def get_all_tasks(loop: Optional[AbstractEventLoop] = None) -> List[Task]:
"""
Get a list of all tasks for the current loop
"""
return cast(List[Task], _asyncio_get_tasks(loop))
2 changes: 1 addition & 1 deletion plugins/core/cap.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ async def handle_available_caps(conn, caplist, event, irc_paramlist, bot):
]
results = await asyncio.gather(*tasks)
if any(ok and (res or res is None) for ok, res in results):
cap_queue[name_cf] = async_util.create_future(conn.loop)
cap_queue[name_cf] = conn.loop.create_future()
conn.cmd("CAP", "REQ", name)

if irc_paramlist[2] != "*":
Expand Down
5 changes: 2 additions & 3 deletions plugins/core/sasl.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import logging

from cloudbot import hook
from cloudbot.util import async_util

logger = logging.getLogger("cloudbot")

Expand All @@ -18,14 +17,14 @@ async def sasl_ack(conn):
sasl_auth = conn.config.get("sasl")
if sasl_auth and sasl_auth.get("enabled", True):
sasl_mech = sasl_auth.get("mechanism", "PLAIN").upper()
auth_fut = async_util.create_future(conn.loop)
auth_fut = conn.loop.create_future()
conn.memory["sasl_auth_future"] = auth_fut
conn.cmd("AUTHENTICATE", sasl_mech)
cmd, arg = await auth_fut
if cmd == "908":
logger.warning("[%s|sasl] SASL mechanism not supported", conn.name)
elif cmd == "AUTHENTICATE" and arg[0] == "+":
num_fut = async_util.create_future(conn.loop)
num_fut = conn.loop.create_future()
conn.memory["sasl_numeric_future"] = num_fut
if sasl_mech == "PLAIN":
auth_str = "{user}\0{user}\0{passwd}".format(
Expand Down
5 changes: 2 additions & 3 deletions tests/core_tests/irc_client_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
from cloudbot.client import ClientConnectError
from cloudbot.clients import irc
from cloudbot.event import Event, EventType
from cloudbot.util import async_util
from tests.util.async_mock import AsyncMock

if TYPE_CHECKING:
Expand Down Expand Up @@ -53,7 +52,7 @@ def test_send_closed(event_loop):
class TestLineParsing:
@staticmethod
def wait_tasks(conn, cancel=False):
tasks = async_util.get_all_tasks(conn.loop)
tasks = asyncio.all_tasks(conn.loop)
if cancel:
for task in tasks:
task.cancel()
Expand Down Expand Up @@ -675,7 +674,7 @@ async def test_send_sieve_error(self, caplog_bot):
sieve = object()
proto.bot.plugin_manager.out_sieves = [sieve]
proto.bot.plugin_manager.internal_launch = launch = MagicMock()
fut = async_util.create_future(proto.loop)
fut = proto.loop.create_future()
fut.set_result((False, None))
launch.return_value = fut

Expand Down
3 changes: 1 addition & 2 deletions tests/plugin_tests/cap_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
from cloudbot import hook
from cloudbot.event import Event
from cloudbot.plugin import PluginManager
from cloudbot.util import async_util
from plugins.core import cap
from tests.util.mock_module import MockModule

Expand Down Expand Up @@ -66,7 +65,7 @@ def cmd(cmd, subcmd, *args):
bot=event.bot,
conn=event.conn,
)
async_util.wrap_future(cap.on_cap(p, cmd_event), loop=event.loop)
asyncio.ensure_future(cap.on_cap(p, cmd_event), loop=event.loop)

with patch.object(event.conn, "cmd", new=cmd):
res = await cap.on_cap(params, event)
Expand Down
3 changes: 1 addition & 2 deletions tests/util/mock_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
from cloudbot.bot import CloudBot
from cloudbot.client import Client
from cloudbot.plugin import PluginManager
from cloudbot.util.async_util import create_future
from tests.util.mock_config import MockConfig
from tests.util.mock_db import MockDB

Expand All @@ -28,7 +27,7 @@ def __init__(
self.data_dir = str(self.data_path)
self.plugin_dir = self.base_dir / "plugins"
if self.loop:
self.stopped_future: Awaitable[bool] = create_future(self.loop)
self.stopped_future: Awaitable[bool] = self.loop.create_future()
else:
self.stopped_future = None

Expand Down

0 comments on commit ee2f7ab

Please sign in to comment.