File size: 10,013 Bytes
5f3e9f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Single-worker queue for long-running generation workflows."""
from __future__ import annotations

import threading
import traceback
import sys
from collections import deque
from dataclasses import dataclass
from typing import Callable

from core.ai_client import unregister_operation
from core import run_manager
from core.workflow_runner import WorkflowContext, publish_run_event
from utils.run_guard import RunRejected, begin_run, end_run


@dataclass
class QueuedJob:
    run_id: str
    operation_id: str
    fn: Callable[[WorkflowContext], None]
    cancel_event: threading.Event
    label: str = "workflow"
    pipeline_enabled: bool = False


_QUEUE: deque[QueuedJob] = deque()
_CURRENT: dict[str, QueuedJob] = {}
_CONDITION = threading.Condition()
_STARTED = False


def _prevent_sleep() -> bool:
    if sys.platform != "win32":
        return False
    try:
        import ctypes

        ES_CONTINUOUS = 0x80000000
        ES_SYSTEM_REQUIRED = 0x00000001
        ES_DISPLAY_REQUIRED = 0x00000002
        ctypes.windll.kernel32.SetThreadExecutionState(
            ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED
        )
        return True
    except Exception:
        return False


def _allow_sleep() -> None:
    if sys.platform != "win32":
        return
    try:
        import ctypes

        ES_CONTINUOUS = 0x80000000
        ctypes.windll.kernel32.SetThreadExecutionState(ES_CONTINUOUS)
    except Exception:
        pass


def _queue_positions() -> dict[str, int]:
    return {job.run_id: index + 1 for index, job in enumerate(_QUEUE)}


def _publish_queue_positions() -> None:
    positions = _queue_positions()
    for job in list(_QUEUE):
        position = positions.get(job.run_id)
        message = f"Queued at position {position}" if position else "Queued"
        run_manager.update_run(
            job.run_id,
            status="queued",
            stage="queued",
            message=message,
            progress=0,
            queue_position=position,
        )
        run_manager.add_event(
            job.run_id,
            event_type="queued",
            stage="queued",
            progress=0,
            message=message,
            data={"queue_position": position},
        )
        publish_run_event(job.run_id, {
            "type": "queued",
            "run_id": job.run_id,
            "operation_id": job.operation_id,
            "message": message,
            "progress": 0,
            "queue_position": position,
        })


def _worker_loop() -> None:
    while True:
        with _CONDITION:
            while not _QUEUE:
                _CONDITION.wait()
            job = _QUEUE.popleft()
            _CURRENT[job.run_id] = job
            _publish_queue_positions()

        _run_job(job)


def _run_job(job: QueuedJob) -> None:
        ctx = WorkflowContext(job.run_id, job.operation_id, job.cancel_event)
        # In classic mode, hold the global single-flight slot for the
        # duration of the job. Pipeline mode deliberately releases that
        # coarse lock and lets the workflow's own phase locks protect
        # screenshots / PowerPoint while AI can overlap.
        slot_held = False
        sleep_guard = False
        try:
            sleep_guard = _prevent_sleep()
            if not job.pipeline_enabled:
                try:
                    begin_run(job.operation_id, "/job-queue", {"run_id": job.run_id})
                    slot_held = True
                except RunRejected as rr:
                    ctx.fail(f"Backend busy: {rr.message}")
                    return
            if job.cancel_event.is_set():
                ctx.cancel()
            else:
                ctx.started(f"{job.label} started")
                job.fn(ctx)
        except Exception as exc:
            traceback.print_exc()
            run = run_manager.get_run(job.run_id)
            if run and run.get("status") not in {"completed", "failed", "cancelled"}:
                ctx.fail(f"Error: {exc}")
        finally:
            if sleep_guard:
                _allow_sleep()
            if slot_held:
                end_run(job.operation_id)
            with _CONDITION:
                _CURRENT.pop(job.run_id, None)
                _publish_queue_positions()


def _ensure_worker() -> None:
    global _STARTED
    with _CONDITION:
        if _STARTED:
            return
        thread = threading.Thread(target=_worker_loop, daemon=True, name="workflow-job-queue")
        thread.start()
        _STARTED = True


def enqueue(
    run_id: str,
    operation_id: str,
    fn: Callable[[WorkflowContext], None],
    cancel_event: threading.Event,
    label: str = "workflow",
    pipeline_enabled: bool = False,
) -> int:
    job = QueuedJob(
        run_id=run_id,
        operation_id=operation_id,
        fn=fn,
        cancel_event=cancel_event,
        label=label,
        pipeline_enabled=pipeline_enabled,
    )
    _ensure_worker()
    with _CONDITION:
        if pipeline_enabled and not _QUEUE and not any(
            not current.pipeline_enabled for current in _CURRENT.values()
        ):
            _CURRENT[job.run_id] = job
            _publish_queue_positions()
            thread = threading.Thread(
                target=_run_job,
                args=(job,),
                daemon=True,
                name=f"workflow-{run_id}",
            )
            thread.start()
            return 1

        _QUEUE.append(job)
        position = len(_QUEUE)
        _publish_queue_positions()
        _CONDITION.notify()
        return position


_SOFT_CANCEL_STAGES = {
    "after_html": ("html_saved", "Cancellation requested. The process will stop after the HTML file is saved."),
    "after_screenshots": ("screenshots_done", "Cancellation requested. The process will stop after screenshots are captured."),
    "after_pptx": ("pptx_built", "Cancellation requested. The process will stop after the PowerPoint deck is saved."),
    "after_video": ("video_export_done", "Cancellation requested. The process will stop after the MP4 export finishes."),
}


def cancel_job(run_id: str, mode: str = "now", delete_outputs: bool = False) -> bool:
    mode = str(mode or "now").strip().lower()
    delete_outputs = bool(delete_outputs)
    with _CONDITION:
        for job in list(_QUEUE):
            if job.run_id == run_id or job.operation_id == run_id:
                job.cancel_event.set()
                _QUEUE.remove(job)
                run_manager.update_run(job.run_id, settings={"delete_outputs_on_cancel": delete_outputs})
                run_manager.finish_run(job.run_id, status="cancelled", message="Operation cancelled before start", progress=0)
                unregister_operation(job.operation_id)
                publish_run_event(job.run_id, {
                    "type": "cancelled",
                    "run_id": job.run_id,
                    "operation_id": job.operation_id,
                    "message": "Operation cancelled before start",
                })
                _publish_queue_positions()
                return True

        current = next(
            (job for job in _CURRENT.values() if job.run_id == run_id or job.operation_id == run_id),
            None,
        )
        if current:
            if mode in _SOFT_CANCEL_STAGES:
                stage, message = _SOFT_CANCEL_STAGES[mode]
                current_run = run_manager.get_run(current.run_id) or {}
                run_manager.update_run(
                    current.run_id,
                    status="running",
                    stage="cancelling",
                    message=message,
                    progress=None,
                    settings={
                        "cancel_after_stage": stage,
                        "delete_outputs_on_cancel": False,
                    },
                )
                publish_run_event(current.run_id, {
                    "type": "progress",
                    "run_id": current.run_id,
                    "operation_id": current.operation_id,
                    "message": message,
                    "stage": "cancelling",
                    "progress": current_run.get("progress", 0),
                })
                return True

            current.cancel_event.set()
            current_run = run_manager.get_run(current.run_id) or {}
            run_manager.update_run(
                current.run_id,
                status="running",
                stage="cancelling",
                message="Cancellation requested. Waiting for the running step to stop.",
                progress=None,
                settings={"delete_outputs_on_cancel": delete_outputs},
            )
            publish_run_event(current.run_id, {
                "type": "progress",
                "run_id": current.run_id,
                "operation_id": current.operation_id,
                "message": "Cancellation requested",
                "stage": "cancelling",
                "progress": current_run.get("progress", 0),
            })
            return True

    return False


def get_queue_snapshot() -> dict:
    with _CONDITION:
        running = list(_CURRENT.values())
        return {
            "running": {
                "run_id": running[0].run_id,
                "operation_id": running[0].operation_id,
                "label": running[0].label,
            } if running else None,
            "running_all": [
                {
                    "run_id": job.run_id,
                    "operation_id": job.operation_id,
                    "label": job.label,
                    "pipeline_enabled": job.pipeline_enabled,
                }
                for job in running
            ],
            "queued": [
                {
                    "run_id": job.run_id,
                    "operation_id": job.operation_id,
                    "label": job.label,
                    "position": index + 1,
                }
                for index, job in enumerate(_QUEUE)
            ],
        }