# Copyright (c) Huawei Technologies Co., Ltd. 2026-2026. All rights reserved.
# OpenOLC is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#         `http://license.coscl.org.cn/MulanPSL2`
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.

import logging

from olc.task_schedule.task_schedule import Task, OlcScheduleManager

logger = logging.getLogger(__name__)


class OlcClusterLimiterRefresh(Task):
    """
    集群流控批量刷新任务
    """

    def run(self):
        # 方法内引入,防止在未使用集群流控时引入多余依赖
        from olc.limit.cluster.redis.redis_client import OlcRedisManager
        if not OlcRedisManager.check_initialized():
            return

        from olc.limit.cluster.abs_cluster_limiter import AbsClusterLimiter
        # 尽在降级模式下需要探测恢复
        if not AbsClusterLimiter.is_exception_status():
            return

        if OlcRedisManager.is_active():
            logging.info(f"redis connection recovered, cluster mode restored")
            AbsClusterLimiter.recover()

    @classmethod
    def start(cls):
        """
            启动定时任务
        :return:
        """
        try:
            schedule_mgr = OlcScheduleManager.get_instance()
            schedule_mgr.create_task(
                name="olc-cluster-refresh",
                task=OlcClusterLimiterRefresh(),
                interval=1,
                pool_name="olc-cluster-refresh",
                max_worker=1,
            )
            schedule_mgr.start_task(name="olc-cluster-refresh")
        except Exception as e:
            logger.warning(f"failed to start cluster-refresh task: {e}")