def servers_port(response_map):
    for port in range(49_152, 65_535):
        server_process = Process(target=async_http_test_server,
                                 args=(port, response_map))
        server_process.start()
        blocking_sleep(1)  # See if server starts up on requested port.
        if server_process.exitcode is None:
            break
    def test_listing(self, db, chronograph, auction):
        auction.prepare_auction_document()
        db.view('chronograph/start_date')

        chronograph.join(0.1)

        assert job_is_added()
        assert job_is_not_active()

        blocking_sleep(3.4)
        assert job_is_not_added()
        assert job_is_active()
Beispiel #3
0
    async def reschedule(
        self,
        ctx_api: Union["ABCAPI", "API"],
        method: str,
        data: dict,
        recent_response: Any,
    ) -> dict:
        logger.debug(
            "Usage of blocking rescheduler is assumed when VK doesn't respond to "
            "all requests for an amount of time. Starting..."
        )

        attempt_number = 1
        while not isinstance(recent_response, dict):
            logger.info(f"Attempt number {attempt_number}. Making request...")
            blocking_sleep(self.delay * attempt_number)
            recent_response = await ctx_api.request(method, data)
            attempt_number += 1
            logger.debug(f"Attempt succeed? - {isinstance(recent_response, dict)}")

        logger.info(f"Finally succeed after {self.delay ** attempt_number} seconds")
        return recent_response
Beispiel #4
0
    async def reschedule(
        self,
        ctx_api: typing.Union["ABCAPI", "API"],
        method: str,
        data: dict,
        recent_response: typing.Any,
    ) -> dict:
        logger.debug(
            "Tottle uses request_rescheduler when Telegram "
            "doesn't respond properly for an amount of time. Starting..."
        )

        attempt_number = 1
        while not isinstance(recent_response, dict):
            logger.info(f"Attempt №{attempt_number}. Making request...")
            blocking_sleep(self.delay * attempt_number)
            recent_response = await ctx_api.request(method, data)
            attempt_number += 1
            logger.debug(f"Attempt succeed? - {isinstance(recent_response, dict)}")

        logger.info(f"Finally succeed after {self.delay ** attempt_number} seconds!")
        return recent_response
Beispiel #5
0
def wait_for_interruption():
    """
    Waits for keyboard interruption. If occurred, shuts down all the clients and closes the event loop. This operation
    is unreleasable.
    
    > Shutting down the clients might take a few seconds depending on the added shutdown event handlers.
    
    Raises
    ------
    RuntimeError
        If used inside of the event loop of clients.
    KeyboardInterrupt
        The received keyboard interrupt.
    """
    if current_thread() is KOKORO:
        raise RuntimeError(
            f'`wait_for_interruption` cannot be used inside of {KOKORO!r}.')

    try:
        while True:
            # sleep 1 day
            blocking_sleep(86400.0)
    except KeyboardInterrupt as err:
        exception = err
    else:
        # should not happen
        exception = None

    sys.stdout.write('wait_for_interruption interrupted\n')

    WaitTillAll(
        [Task(client.disconnect(), KOKORO) for client in CLIENTS.values()],
        KOKORO).sync_wrap().wait()
    KOKORO.stop()

    # reraise exception
    if (exception is not None):
        raise exception
Beispiel #6
0
    def run(self):
        voice_client = self.client
        start = perf_counter()
        loops = 0

        try:
            while True:
                if not self.resumed.is_set():
                    self.resumed.wait()
                    start = perf_counter()
                    loops = 0
                    continue

                #are we disconnected from voice?
                if not voice_client.connected.is_set():
                    voice_client.connected.wait()
                    start = perf_counter()
                    loops = 0
                    continue

                loops += 1
                data = self.source.read()

                if self.done or (not data):
                    self.resumed.clear()
                    self.source.cleanup()
                    self.source = None
                    if voice_client.lock.locked():
                        voice_client.lock.acquire()
                    else:
                        with voice_client.lock:
                            stop = voice_client.loop.create_task_threadsafe(
                                voice_client.call_after(
                                    voice_client,
                                    lock=False)).syncwrap().wait()
                        if stop:
                            self.done = True
                            self.resumed.set()
                            break

                    continue

                sequence = voice_client._sequence
                if sequence == 65535:
                    sequence = 0
                else:
                    sequence = sequence + 1
                voice_client._sequence = sequence

                if self.source.NEEDS_ENCODE:
                    data = voice_client._encoder.encode(data)

                header = b''.join([
                    b'\x80x',
                    voice_client._sequence.to_bytes(2, 'big'),
                    voice_client._timestamp.to_bytes(4, 'big'),
                    voice_client._source.to_bytes(4, 'big'),
                ])

                nonce = header + b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
                packet = bytearray(header) + voice_client._secret_box.encrypt(
                    bytes(data), nonce).ciphertext

                try:
                    voice_client.socket.sendto(
                        packet,
                        (voice_client._endpoint_ip, voice_client._voice_port))
                except BlockingIOError:
                    pass

                timestamp = voice_client._timestamp + SAMPLES_PER_FRAME
                if timestamp > 4294967295:
                    timestamp = 0
                voice_client._timestamp = timestamp

                delay = PLAYER_DELAY + (
                    (start + PLAYER_DELAY * loops) - perf_counter())
                if delay < .0:
                    continue
                blocking_sleep(delay)
        except BaseException as err:
            extracted = [
                'Exception occured at \n',
                self.__repr__(),
                '\n',
            ]
            render_exc_to_list(err, extend=extracted)
            sys.stderr.write(''.join(extracted))

            voice_client.player = None
            self.done = True
            self.resumed.set()
            self.source.cleanup()