Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Рефакторинг рекурсии файла фиксации простоев #97

Open
ArtemBalandin81 opened this issue Oct 15, 2024 · 0 comments
Labels
refactoring Refactorings and optimizations

Comments

@ArtemBalandin81
Copy link
Owner

Why?

  • Проверить, что счетчик считается дважды (двойной слип)
  • Избавиться от рекурсии

How Does It Work Now?

  • Сейчас рекурсия и двойной слип (возможно)
  • Возможет затык рекурсии после 1000 итераций (требует проверки)

How To Do?

  • посмотреть возможность упростить файл по образцу
    async def check_connection(
            self,
            CONNECTION_TEST_URL_BASE: str = settings.CONNECTION_TEST_URL_BASE,
            CONNECTION_TEST_URL_2: str = settings.CONNECTION_TEST_URL_2
    ) -> dict[str, int | str]:
        """ Проверяет наличие доступа к интернет."""
        try:
            status_code_base_url = requests.get(CONNECTION_TEST_URL_BASE).status_code
        # если ошибка соединения с базовым сайтом, то тест сайта Яндекс
        # если и сайта Яндекс не доступен - в run_check_connection() вызывается except!
        except requests.exceptions.ConnectionError:
            await log.aerror(FAILED_GET_URL, url=CONNECTION_TEST_URL_BASE)
            status_code_url_ya = requests.get(CONNECTION_TEST_URL_2).status_code
            info_connections = {
                CONNECTION_TEST_URL_BASE: URL_CONNECTION_ERROR,
                CONNECTION_TEST_URL_2: status_code_url_ya,
                TIME_INFO: datetime.now(TZINFO).isoformat(timespec='seconds')
            }
            await log.ainfo(INFO_CONNECTIONS, info_connections=info_connections)
            return info_connections
        info_connections = {
            CONNECTION_TEST_URL_BASE: status_code_base_url,
            CONNECTION_TEST_URL_2: SUPPOSE_OK,
            TIME_INFO: datetime.now(TZINFO).isoformat(timespec='seconds')
        }
        await log.ainfo(INFO_CONNECTIONS, info_connections=info_connections)
        return info_connections

    async def run_create_suspension(self, suspension_object: dict | None) -> None:
        """ Запускает тестовое сохранение случая простоя в БД."""
        if suspension_object is None:
            suspension_object = self.suspension_example
        suspension = Suspension(**suspension_object)
        async with self._sessionmaker() as session:
            suspension_repository = SuspensionRepository(session)
            await suspension_repository.create(suspension)
            await log.ainfo(SUSPENSION_DB_LOADED, suspension=suspension)

    async def run_check_connection(
            self,
            time_counter: int = settings.SLEEP_TEST_CONNECTION,
            suspension_start: bool | datetime = None,
    ) -> None:
        """ Запускает периодический процесс тестирование доступа к интернет и сохранение в БД простоев."""

        while True:
            try:
                await asyncio.sleep(settings.SLEEP_TEST_CONNECTION)
                await self.check_connection(settings.CONNECTION_TEST_URL_BASE, settings.CONNECTION_TEST_URL_2)
                if time_counter != settings.SLEEP_TEST_CONNECTION:  # Нач. счетчик простоя = интервалу теста соединения
                    await log.ainfo(
                        SUSPENSION_CREATED,
                        start=str(suspension_start),
                        finish=datetime.now(TZINFO).isoformat(timespec='seconds'),
                        counter=time_counter
                    )
                    suspension = self.suspension_example.copy()  # фиксируется время простоя и заносится в БД
                    suspension["suspension_start"] = suspension_start
                    suspension["suspension_finish"] = datetime.now(TZINFO)
                    await self.run_create_suspension(suspension)
                    time_counter = settings.SLEEP_TEST_CONNECTION  # обнуляем счетчик, если соединение восстановилось
                    suspension_start = None  # обнуляем счетчик времени старта простоя
            except requests.exceptions.ConnectionError:  # если ошибка соединения
                await log.aerror(FAILED_GET_URL, url=settings.CONNECTION_TEST_URL_2)
                time_counter += settings.SLEEP_TEST_CONNECTION
                suspension_start = suspension_start or datetime.now(TZINFO)
                if time_counter == settings.SLEEP_TEST_CONNECTION:
                    await log.ainfo(FIRST_COUNTER, counter=time_counter, suspension_start=str(suspension_start))
                else:
                    await log.ainfo(
                        TIME_COUNTER,
                        counter=time_counter,
                        err=ConnectionError,
                        url=settings.CONNECTION_TEST_URL_2
                    )
                time_counter += settings.SLEEP_TEST_CONNECTION

Where?

src/somewhere.py
src/somewhere/somewhere/somewhere.py

@ArtemBalandin81 ArtemBalandin81 added the refactoring Refactorings and optimizations label Oct 15, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
refactoring Refactorings and optimizations
Projects
None yet
Development

No branches or pull requests

1 participant