Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
"""
def thread_worker():
nonlocal last_active
run_async_from_thread(sleep_event.set)
time.sleep(0.2)
last_active = 'thread'
run_async_from_thread(finish_event.set)
async def task_worker():
nonlocal last_active
try:
await run_sync_in_worker_thread(thread_worker, cancellable=cancellable)
finally:
last_active = 'task'
sleep_event = create_event()
finish_event = create_event()
last_active = None
async with create_task_group() as tg:
await tg.spawn(task_worker)
await sleep_event.wait()
await tg.cancel_scope.cancel()
await finish_event.wait()
assert last_active == expected_last_active
async def test_event_cancel(self):
async def task():
nonlocal task_started, event_set
task_started = True
await event.wait()
event_set = True
task_started = event_set = False
event = create_event()
async with create_task_group() as tg:
await tg.spawn(task)
await tg.cancel_scope.cancel()
await event.set()
assert task_started
assert not event_set
self._connection_subprotocol = None
self._handshake_headers = None
self._headers = headers
self.message_queue_size = message_queue_size
self.max_message_size = max_message_size
self._reject_status = None
self._reject_headers = None
self._reject_body = b''
self._stream_lock = anyio.create_lock()
self._message_size = 0
self._message_parts = []
self._event_queue = anyio.create_queue(self.message_queue_size)
self._pings = OrderedDict()
self._open_handshake = anyio.create_event()
self._close_handshake = anyio.create_event()
def __init__(self, library, shard_count=-1, prefixes='py.', message_cache_max=2500, **kwargs):
super().__init__()
sniffio.current_async_library_cvar.set(library)
self.token = ''
self.is_bot = True
self._boot_up_time = None
self.running = anyio.create_event()
self.api = HttpClient(self)
self.session = asks.Session() # public session
self.shards = [] if shard_count < 1 else list(range(shard_count))
self.users = Collection(User)
self.guilds = Collection(Guild)
self.channels = Collection(Channel)
self.messages = deque(maxlen=message_cache_max)
self.commands = CommandCollection(self)
self.webhooks = Collection(Webhook, indexor='name')
self.prefixes = prefixes if isinstance(prefixes, list) else [prefixes]
self._nonces = dict()
self.user = None
def __init__(self, session: _GatewayState):
#: The current session being used for this gateway.
self.session = session
#: The current heartbeat stats being used for this gateway.
self.heartbeat_stats = HeartbeatStats()
#: The current :class:`.BasicWebsocketWrapper` connected to Discord.
self.websocket: UniversalWrapper = None
#: The current task group for this gateway.
self.task_group: TaskGroup = None
self._logger = None
self._stop_heartbeating = anyio.create_event()
self._dispatches_handled = Counter()
# used for zlib-streaming
self._databuffer = bytearray()
self._decompressor = zlib.decompressobj()
def suspend(self) -> None:
"""Temporarily suspends the hotplug detector."""
self._suspended += 1
if self._suspended and not self._resume_event:
self._resume_event = create_event()
self._handshake_headers = None
self._headers = headers
self.message_queue_size = message_queue_size
self.max_message_size = max_message_size
self._reject_status = None
self._reject_headers = None
self._reject_body = b''
self._stream_lock = anyio.create_lock()
self._message_size = 0
self._message_parts = []
self._event_queue = anyio.create_queue(self.message_queue_size)
self._pings = OrderedDict()
self._open_handshake = anyio.create_event()
self._close_handshake = anyio.create_event()
def __init__(self, client):
self.client = client
self.token = client.token
self.retries = 5
self.buckets = defaultdict(anyio.create_lock)
self.global_event = anyio.create_event()
# set global lock and create user agent
user_agent = 'DiscordBot ({0} {1}) Python/{2[0]}.{2[1]}'
self.user_agent = user_agent.format(
__github__, __version__, sys.version_info)
token = 'Bot {.token}'.format(self) if self.client.is_bot else self.token
headers = {
"Authorization": token,
"User-Agent": self.user_agent
}
self.session = asks.Session(headers=headers)
#: The number of numbers this guild has.
#: This is automatically updated.
self.member_count = 0 # type: int
#: The maximum number of members this guild can have.
self.max_members: int = 0
#: The maximum number of presences this guild can have.
self.max_presences: int = 0
#: Is this guild a large guild according to Discord?
self._large = False # type: bool
#: Has this guild finished chunking?
self._finished_chunking = anyio.create_event()
self._chunks_left = 0
#: The current voice client associated with this guild.
self.voice_client = None
#: The :class:`.GuildChannelWrapper` that wraps the channels in this Guild.
self.channels = GuildChannelWrapper(self)
#: The :class:`.GuildRoleWrapper` that wraps the roles in this Guild.
self.roles = GuildRoleWrapper(self)
#: The :class:`.GuildEmojiWrapper` that wraps the emojis in this Guild.
self.emojis = GuildEmojiWrapper(self)
#: The :class:`.GuildBanContainer` for this Guild.
self.bans = GuildBanContainer(self)
def __init__(self, grpc_connection: GRPCConnection, stream_id: int, socket: SocketWrapper,
grpc_socket: "GRPCSocket"):
self._stream_id = stream_id
self._grpc_connection = grpc_connection
self._grpc_socket = grpc_socket
self._socket = socket
self._flow_control_update_event = anyio.create_event()
self._incoming_events = anyio.create_queue(sys.maxsize)
self._response_started = False
self._state = GRPCStreamState.OPEN
self._start_stream_event = None
self._end_stream_event = None