# -*- coding: utf-8 -*-
"""
@File    : test_redis_rate_limit.py
@Author  : Jay
@Date    : 2026/3/19 15:49
@Desc    : 测试限流功能
"""
import json
import random

from redis_xsync import register_redis
from redis_xsync.rtypes import LimitedModel


def test_redis_rate_limit_sync(limiter):
    with limiter(redis_key="crawler:identity:flow_limit") as lt:
        while True:
            print(json.loads(lt.wait_ask_available_containers(quantity=1, timeout=10)))


async def test_redis_rate_limit(limiter):
    async with limiter(redis_key="crawler:identity:flow_limit") as lt:
        i = 1
        while True:
            await lt.set_available_containers(LimitedModel(
                id=f'test_{i}',
                ttl_ms=random.randint(30000, 60000),
                interval_ms=0,
                containers="cookies"
            ))
            i += 1
            await asyncio.sleep(.5)


if __name__ == '__main__':
    import asyncio, threading

    cfg = {
        'host': '127.0.0.1',
        'port': 6379,
        'db': 0,
        'password': '',
        'decode_responses': True
    }
    redisXsync = register_redis(label='redis_xsync', **cfg)
    Limited = redisXsync.Limited
    threading.Thread(target=test_redis_rate_limit_sync, args=(Limited,)).start()
    asyncio.run(test_redis_rate_limit(Limited))
