File size: 11,647 Bytes
17f77b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
# ============================================================
# 🔄 ASYNC MANAGER - Execução Segura sem Bloqueio
# ============================================================
"""
Gerenciador de tarefas assíncronas para garantir que:
1. Respostas NUNCA travam (resposta retornada IMEDIATAMENTE)
2. Treinamento executa em background ISOLADO
3. Database access é sincronizado
4. Múltiplas requisições não competem por recursos
"""

import asyncio
import threading
import time
import queue
from typing import Callable, Any, Optional, Dict, List
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from loguru import logger

# ============================================================
# 📋 ESTRUTURAS DE DADOS
# ============================================================

@dataclass
class AsyncTask:
    """Representa uma tarefa assíncrona"""
    task_id: str
    name: str
    func: Callable
    args: tuple = field(default_factory=tuple)
    kwargs: dict = field(default_factory=dict)
    priority: int = 0  # 0=low, 1=medium, 2=high
    created_at: datetime = field(default_factory=datetime.now)
    started_at: Optional[datetime] = None
    completed_at: Optional[datetime] = None
    status: str = "queued"  # queued, running, completed, failed
    error: Optional[str] = None
    result: Any = None
    timeout: float = 30.0  # segundos


class ResponseBlockManager:
    """Gerencia execução de tarefas sem bloquear respostas API"""
    
    def __init__(self, max_workers: int = 3, queue_size: int = 100):
        self.max_workers = max_workers
        self.queue_size = queue_size
        self._task_queue = queue.PriorityQueue(maxsize=queue_size)
        self._running_tasks: Dict[str, AsyncTask] = {}
        self._completed_tasks: List[AsyncTask] = []
        self._workers: List[threading.Thread] = []
        self._running = False
        self._lock = threading.Lock()
        
        # Stats
        self._stats = {
            "total_tasks": 0,
            "completed_tasks": 0,
            "failed_tasks": 0,
            "avg_task_time": 0.0,
            "queue_depth": 0
        }
        
        logger.info(f"🔄 ResponseBlockManager inicializado ({max_workers} workers, queue_size={queue_size})")
    
    def start(self):
        """Inicia workers"""
        if self._running:
            return
        
        self._running = True
        for i in range(self.max_workers):
            worker = threading.Thread(
                target=self._worker_loop,
                name=f"AsyncWorker-{i}",
                daemon=True
            )
            worker.start()
            self._workers.append(worker)
        
        logger.success(f"✅ {self.max_workers} workers iniciados")
    
    def stop(self, timeout: float = 10.0):
        """Para workers com timeout"""
        self._running = False
        
        # Aguarda workers terminarem
        for worker in self._workers:
            worker.join(timeout=timeout / len(self._workers))
        
        logger.info("⏹️ ResponseBlockManager parado")
    
    def queue_task(
        self,
        name: str,
        func: Callable,
        args: tuple = (),
        kwargs: Optional[Dict] = None,
        priority: int = 0,
        timeout: float = 30.0,
        task_id: Optional[str] = None
    ) -> str:
        """
        Enfileira tarefa para execução em background
        
        Returns: task_id para rastreamento
        """
        if not self._running:
            logger.warning("⚠️ ResponseBlockManager não está rodando")
            return ""
        
        # Gera ID se não fornecido
        if not task_id:
            task_id = f"{name}_{int(time.time() * 1000)}"
        
        task = AsyncTask(
            task_id=task_id,
            name=name,
            func=func,
            args=args,
            kwargs=kwargs or {},
            priority=priority,
            timeout=timeout
        )
        
        try:
            # Enfileira com prioridade (inverte para usar max heap)
            self._task_queue.put((-priority, time.time(), task), timeout=1.0)
            
            with self._lock:
                self._stats["total_tasks"] += 1
                self._stats["queue_depth"] = self._task_queue.qsize()
            
            logger.debug(f"📥 Task enfileirada: {name} (id={task_id}, priority={priority})")
            return task_id
        
        except queue.Full:
            logger.error(f"❌ Fila de tarefas cheia! Ignorando: {name}")
            return ""
    
    def _worker_loop(self):
        """Loop de execução de tarefas"""
        while self._running:
            try:
                # Espera por tarefa com timeout
                try:
                    _, _, task = self._task_queue.get(timeout=1.0)
                except queue.Empty:
                    continue
                
                # Marca como em execução
                with self._lock:
                    self._running_tasks[task.task_id] = task
                    task.status = "running"
                    task.started_at = datetime.now()
                
                logger.debug(f"⚙️ Executando: {task.name} (id={task.task_id})")
                
                # Executa com timeout
                try:
                    result = self._execute_with_timeout(task)
                    task.result = result
                    task.status = "completed"
                    
                    with self._lock:
                        self._stats["completed_tasks"] += 1
                        self._completed_tasks.append(task)
                    
                    logger.success(f"✅ Task completada: {task.name}")
                
                except TimeoutError:
                    task.status = "failed"
                    task.error = f"Timeout ({task.timeout}s)"
                    with self._lock:
                        self._stats["failed_tasks"] += 1
                    logger.error(f"❌ Task timeout: {task.name}")
                
                except Exception as e:
                    task.status = "failed"
                    task.error = str(e)
                    with self._lock:
                        self._stats["failed_tasks"] += 1
                    logger.error(f"❌ Task failed: {task.name} - {e}")
                
                finally:
                    # Remove de running
                    with self._lock:
                        task.completed_at = datetime.now()
                        if task.task_id in self._running_tasks:
                            del self._running_tasks[task.task_id]
                        
                        # Calcula tempo médio
                        if task.completed_at and task.started_at:
                            elapsed = (task.completed_at - task.started_at).total_seconds()
                            self._stats["avg_task_time"] = (
                                self._stats["avg_task_time"] * 0.8 + elapsed * 0.2
                            )
            
            except Exception as e:
                logger.exception(f"Erro fatal em worker: {e}")
    
    def _execute_with_timeout(self, task: AsyncTask) -> Any:
        """Executa função com timeout"""
        result_container = {}
        exception_container = {}
        
        def _wrapper():
            try:
                result = task.func(*task.args, **task.kwargs)
                result_container['result'] = result
            except Exception as e:
                exception_container['error'] = e
        
        thread = threading.Thread(target=_wrapper, daemon=False)
        thread.start()
        thread.join(timeout=task.timeout)
        
        if thread.is_alive():
            raise TimeoutError(f"Execução não completou em {task.timeout}s")
        
        if 'error' in exception_container:
            raise exception_container['error']
        
        return result_container.get('result')
    
    def get_task_status(self, task_id: str) -> Dict[str, Any]:
        """Retorna status de uma tarefa"""
        # Procura em running
        if task_id in self._running_tasks:
            task = self._running_tasks[task_id]
            return {
                "id": task_id,
                "name": task.name,
                "status": task.status,
                "started_at": task.started_at.isoformat() if task.started_at else None,
                "completed_at": None  # ainda em execução
            }
        
        # Procura em completed
        for task in reversed(self._completed_tasks[-100:]):  # últimas 100
            if task.task_id == task_id:
                return {
                    "id": task_id,
                    "name": task.name,
                    "status": task.status,
                    "started_at": task.started_at.isoformat() if task.started_at else None,
                    "completed_at": task.completed_at.isoformat() if task.completed_at else None,
                    "error": task.error,
                    "result": task.result
                }
        
        return {"id": task_id, "status": "not_found"}
    
    def get_stats(self) -> Dict[str, Any]:
        """Retorna estatísticas"""
        with self._lock:
            return {
                **self._stats,
                "running_tasks": len(self._running_tasks),
                "completed_history": len(self._completed_tasks),
                "workers_active": len([w for w in self._workers if w.is_alive()])
            }
    
    def clear_history(self):
        """Limpa histórico de tarefas completadas"""
        with self._lock:
            self._completed_tasks.clear()
            logger.info("📊 Histórico de tarefas limpo")


# ============================================================
# 🌐 INSTÂNCIA GLOBAL
# ============================================================

# Inicializa com 3 workers (não-bloqueante)
async_manager = ResponseBlockManager(max_workers=3, queue_size=100)

# Inicia automaticamente ao importar
try:
    async_manager.start()
except Exception as e:
    logger.warning(f"⚠️ Erro ao iniciar async_manager: {e}")


# ============================================================
# 🎯 HELPERS
# ============================================================

def queue_training_task(
    func: Callable,
    args: tuple = (),
    kwargs: Optional[Dict] = None,
    task_id: Optional[str] = None
) -> str:
    """Enfileira tarefa de treinamento (baixa prioridade)"""
    return async_manager.queue_task(
        name="training",
        func=func,
        args=args,
        kwargs=kwargs,
        priority=0,  # baixa prioridade
        timeout=60.0,  # timeout maior para treinamento
        task_id=task_id
    )


def queue_data_task(
    func: Callable,
    args: tuple = (),
    kwargs: Optional[Dict] = None,
    task_id: Optional[str] = None
) -> str:
    """Enfileira tarefa de armazenamento de dados (média prioridade)"""
    return async_manager.queue_task(
        name="data_storage",
        func=func,
        args=args,
        kwargs=kwargs,
        priority=1,  # média prioridade
        timeout=10.0,
        task_id=task_id
    )


def queue_urgent_task(
    func: Callable,
    args: tuple = (),
    kwargs: Optional[Dict] = None,
    task_id: Optional[str] = None
) -> str:
    """Enfileira tarefa urgente (alta prioridade)"""
    return async_manager.queue_task(
        name="urgent",
        func=func,
        args=args,
        kwargs=kwargs,
        priority=2,  # alta prioridade
        timeout=5.0,
        task_id=task_id
    )