File size: 14,871 Bytes
7782338
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
# # queue.py
# import os
# import time
# import pickle
# import asyncio
# import nest_asyncio
# from pathlib import Path
# from enum import Enum
# from collections import deque
# from concurrent.futures import ThreadPoolExecutor
# from typing import Callable, Optional

# # allow nested event loops in some environments
# nest_asyncio.apply()


# class TaskStatus(Enum):
#     QUEUED = "queued"
#     RUNNING = "running"
#     COMPLETED = "completed"
#     FAILED = "failed"
#     CANCELLED = "cancelled"


# class TaskQueue:
#     """
#     File-backed persistent queue that stores tasks as metadata dicts.
#     Uses ThreadPoolExecutor to run CPU-bound pipeline in worker threads.
#     """
#     def __init__(self, base_dir: Path | str, max_workers: int = 2):
#         self.base_dir = Path(base_dir)
#         self.base_dir.mkdir(parents=True, exist_ok=True)
#         self._queue_file = self.base_dir / "queue.pkl"
#         self._state_file = self.base_dir / "state.pkl"

#         self._dq = deque()  # stores metadata dicts
#         self._tasks = {}  # task_id -> metadata
#         self._statuses = {}  # task_id -> TaskStatus
#         self._lock = asyncio.Lock()

#         self._executor = ThreadPoolExecutor(max_workers=max_workers)
#         self._worker_task: Optional[asyncio.Task] = None
#         self._shutdown = False
#         self._processor: Optional[Callable] = None  # sync function to run per task

#         self._load_state()

#     # ------------------------
#     # persistence
#     # ------------------------
#     def _save_state(self):
#         try:
#             tmp = self._state_file.with_suffix(".tmp")
#             with tmp.open("wb") as f:
#                 pickle.dump({
#                     "queue": list(self._dq),
#                     "tasks": self._tasks,
#                     "statuses": self._statuses,
#                 }, f)
#             tmp.replace(self._state_file)
#         except Exception:
#             # do not crash app on disk save error; log in real app
#             pass

#     def _load_state(self):
#         if self._state_file.exists():
#             try:
#                 with self._state_file.open("rb") as f:
#                     data = pickle.load(f)
#                 for item in data.get("queue", []):
#                     self._dq.append(item)
#                 self._tasks.update(data.get("tasks", {}))
#                 self._statuses.update(data.get("statuses", {}))
#             except Exception:
#                 # if corrupted, start fresh
#                 self._dq = deque()
#                 self._tasks = {}
#                 self._statuses = {}

#     # ------------------------
#     # public API
#     # ------------------------
#     def enqueue(self, task_meta: dict):
#         task_id = task_meta.get("task_id")
#         if not task_id:
#             raise ValueError("task_meta must contain 'task_id'")

#         self._dq.append(task_meta)
#         self._tasks[task_id] = task_meta
#         self._statuses[task_id] = TaskStatus.QUEUED
#         self._save_state()

#     def get_status(self, task_id: str):
#         return self._statuses.get(task_id)

#     def get_task_info(self, task_id: str):
#         return self._tasks.get(task_id)

#     def remove_task(self, task_id: str):
#         # Remove from tasks and statuses; queue items will be filtered by worker
#         self._tasks.pop(task_id, None)
#         self._statuses.pop(task_id, None)
#         self._save_state()

#     # ------------------------
#     # lifecycle
#     # ------------------------
#     async def start(self, processor: Callable):
#         """Start the background worker loop. processor should be a sync function accept task_meta."""
#         if self._worker_task:
#             return
#         self._processor = processor
#         self._shutdown = False
#         loop = asyncio.get_event_loop()
#         self._worker_task = loop.create_task(self._worker_loop())

#     async def stop(self):
#         self._shutdown = True
#         if self._worker_task:
#             await self._worker_task
#             self._worker_task = None
#         self._executor.shutdown(wait=True)
#         self._save_state()

#     # ------------------------
#     # worker loop
#     # ------------------------
#     async def _worker_loop(self):
#         logger.info("πŸ”„ Worker loop started")
#         while not self._shutdown:
#             if not self._dq:
#                 await asyncio.sleep(0.5)
#                 continue

#             task_meta = self._dq.popleft()
#             task_id = task_meta.get("task_id")
#             logger.info(f"Processing task {task_id}")

#             try:
#                 self._statuses[task_id] = TaskStatus.RUNNING
#                 self._save_state()

#                 loop = asyncio.get_event_loop()
#                 logger.debug(f"Running processor for task {task_id}")
#                 future = loop.run_in_executor(
#                     self._executor, 
#                     self._run_processor_safe, 
#                     task_meta
#                 )
#                 result = await future
#                 logger.debug(f"Processor result: {result}")

#                 if isinstance(result, dict) and result.get("success"):
#                     self._statuses[task_id] = TaskStatus.COMPLETED
#                     self._tasks[task_id].update({
#                         "output_path": result.get("output_path"),
#                         "output_bytes": result.get("output_bytes")
#                     })
#                     logger.info(f"Task {task_id} completed successfully")
#                 else:
#                     self._statuses[task_id] = TaskStatus.FAILED
#                     logger.error(f"Task {task_id} failed: {result}")

#                 self._save_state()
#             except Exception as e:
#                 logger.exception(f"Error processing task {task_id}")
#                 self._statuses[task_id] = TaskStatus.FAILED
#                 self._save_state()

#             await asyncio.sleep(0.1)

#         logger.info("πŸ”š Worker loop exiting cleanly.")

#     def _run_processor_safe(self, task_meta: dict) -> dict:
#         try:
#             if not self._processor:
#                 logger.error("❌ No processor configured, cannot run task.")
#                 return {"success": False, "error": "No processor configured"}

#             task_id = task_meta.get("task_id")
#             logger.debug(f"🚧 Running processor for task {task_id}...")
#             result = self._processor(task_meta)
#             logger.debug(f"🎯 Processor result for {task_id}: {result}")
#             return result or {"success": False}
#         except Exception as e:
#             logger.exception(f"πŸ’₯ Processor crashed for task {task_meta.get('task_id')}: {e}")
#             return {"success": False, "error": str(e)}




# queue.py
import os
import time
import pickle
import asyncio
import nest_asyncio
from pathlib import Path
from enum import Enum
from collections import deque
from concurrent.futures import ThreadPoolExecutor
from typing import Callable, Optional

# allow nested event loops in some environments
nest_asyncio.apply()

# --------------------------------------------------
# Logging setup
# --------------------------------------------------
import logging

logging.basicConfig(
    level=logging.DEBUG,
    format="🧩 [%(asctime)s] [%(levelname)s] %(message)s",
    datefmt="%H:%M:%S",
)
logger = logging.getLogger("queue_system")


class TaskStatus(Enum):
    QUEUED = "queued"
    RUNNING = "running"
    COMPLETED = "completed"
    FAILED = "failed"
    CANCELLED = "cancelled"


class TaskQueue:
    """

    File-backed persistent queue that stores tasks as metadata dicts.

    Uses ThreadPoolExecutor to run CPU-bound pipeline in worker threads.

    """
    def __init__(self, base_dir: Path | str, max_workers: int = 2):
        self.base_dir = Path(base_dir)
        self.base_dir.mkdir(parents=True, exist_ok=True)
        self._queue_file = self.base_dir / "queue.pkl"
        self._state_file = self.base_dir / "state.pkl"

        self._dq = deque()
        self._tasks = {}
        self._statuses = {}
        self._lock = asyncio.Lock()

        self._executor = ThreadPoolExecutor(max_workers=max_workers)
        self._worker_task: Optional[asyncio.Task] = None
        self._shutdown = False
        self._processor: Optional[Callable] = None

        logger.info(f"πŸš€ TaskQueue initialized | base_dir={self.base_dir} | workers={max_workers}")
        self._load_state()

    # ------------------------
    # persistence
    # ------------------------
    def _save_state(self):
        try:
            tmp = self._state_file.with_suffix(".tmp")
            with tmp.open("wb") as f:
                pickle.dump({
                    "queue": list(self._dq),
                    "tasks": self._tasks,
                    "statuses": self._statuses,
                }, f)
            tmp.replace(self._state_file)
            logger.debug(f"πŸ’Ύ Queue state saved | queued={len(self._dq)} tasks")
        except Exception as e:
            logger.warning(f"⚠️ Failed to save state: {e}")

    def _load_state(self):
        if self._state_file.exists():
            try:
                with self._state_file.open("rb") as f:
                    data = pickle.load(f)
                for item in data.get("queue", []):
                    self._dq.append(item)
                self._tasks.update(data.get("tasks", {}))
                self._statuses.update(data.get("statuses", {}))
                logger.info(f"πŸ“‚ Loaded previous queue state | tasks={len(self._tasks)}")
            except Exception as e:
                logger.error(f"❌ Failed to load state file, starting fresh: {e}")
                self._dq = deque()
                self._tasks = {}
                self._statuses = {}

    # ------------------------
    # public API
    # ------------------------
    def enqueue(self, task_meta: dict):
        task_id = task_meta.get("task_id")
        if not task_id:
            raise ValueError("task_meta must contain 'task_id'")
        self._dq.append(task_meta)
        self._tasks[task_id] = task_meta
        self._statuses[task_id] = TaskStatus.QUEUED
        self._save_state()
        logger.info(f"πŸ†• Task enqueued | id={task_id} | total_queued={len(self._dq)}")

    def get_status(self, task_id: str):
        st = self._statuses.get(task_id)
        logger.debug(f"πŸ“Š get_status({task_id}) β†’ {st}")
        return st

    def get_task_info(self, task_id: str):
        info = self._tasks.get(task_id)
        logger.debug(f"ℹ️ get_task_info({task_id}) β†’ {'found' if info else 'not found'}")
        return info

    def remove_task(self, task_id: str):
        self._tasks.pop(task_id, None)
        self._statuses.pop(task_id, None)
        self._save_state()
        logger.info(f"πŸ—‘ Task removed from system | id={task_id}")

    # ------------------------
    # lifecycle
    # ------------------------
    async def start(self, processor: Callable):
        if self._worker_task:
            logger.warning("⚠️ Queue worker already running, ignoring start request.")
            return
        self._processor = processor
        self._shutdown = False
        loop = asyncio.get_event_loop()
        self._worker_task = loop.create_task(self._worker_loop())
        logger.info("🏁 Background worker started successfully.")

    async def stop(self):
        logger.info("πŸ›‘ Stopping background worker...")
        self._shutdown = True
        if self._worker_task:
            await self._worker_task
            self._worker_task = None
        self._executor.shutdown(wait=True)
        self._save_state()
        logger.info("βœ… Worker stopped and executor shut down cleanly.")

    # ------------------------
    # worker loop
    # ------------------------
    async def _worker_loop(self):
        logger.info("πŸ”„ Worker loop started")
        while not self._shutdown:
            if not self._dq:
                await asyncio.sleep(0.5)
                continue

            task_meta = self._dq.popleft()
            task_id = task_meta.get("task_id")
            logger.info(f"Processing task {task_id}")

            try:
                self._statuses[task_id] = TaskStatus.RUNNING
                self._save_state()

                loop = asyncio.get_event_loop()
                logger.debug(f"Running processor for task {task_id}")
                future = loop.run_in_executor(
                    self._executor, 
                    self._run_processor_safe, 
                    task_meta
                )
                result = await future
                logger.debug(f"Processor result: {result}")

                if isinstance(result, dict) and result.get("success"):
                    self._statuses[task_id] = TaskStatus.COMPLETED
                    self._tasks[task_id].update({
                        "output_path": result.get("output_path"),
                        "output_bytes": result.get("output_bytes")
                    })
                    logger.info(f"Task {task_id} completed successfully")
                else:
                    self._statuses[task_id] = TaskStatus.FAILED
                    logger.error(f"Task {task_id} failed: {result}")

                self._save_state()
            except Exception as e:
                logger.exception(f"Error processing task {task_id}")
                self._statuses[task_id] = TaskStatus.FAILED
                self._save_state()

            await asyncio.sleep(0.1)

        logger.info("πŸ”š Worker loop exiting cleanly.")

    def _run_processor_safe(self, task_meta: dict) -> dict:
        try:
            if not self._processor:
                logger.error("❌ No processor configured, cannot run task.")
                return {"success": False, "error": "No processor configured"}

            task_id = task_meta.get("task_id")
            logger.debug(f"🚧 Running processor for task {task_id}...")
            result = self._processor(task_meta)
            logger.debug(f"🎯 Processor result for {task_id}: {result}")
            return result or {"success": False}
        except Exception as e:
            logger.exception(f"πŸ’₯ Processor crashed for task {task_meta.get('task_id')}: {e}")
            return {"success": False, "error": str(e)}