File size: 1,085 Bytes
aa15bce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
from __future__ import annotations

import asyncio

from ....logging_config import logger
from .summarizer import summarize_conversation

_pending = False
_running = False


def schedule_summarization() -> None:
    """Schedule a background summarization pass if not already queued."""
    global _pending
    _pending = True
    try:
        loop = asyncio.get_running_loop()
    except RuntimeError:
        logger.debug("summarization skipped (no running event loop)")
        return

    if not _running:
        loop.create_task(_run_worker())


async def _run_worker() -> None:
    global _pending, _running
    if _running:
        return

    _running = True
    try:
        while _pending:
            _pending = False
            try:
                await summarize_conversation()
            except Exception as exc:  # pragma: no cover - defensive
                logger.error(
                    "summarization worker failed",
                    extra={"error": str(exc)},
                )
    finally:
        _running = False


__all__ = ["schedule_summarization"]