File size: 7,688 Bytes
c60a316
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
# Adapted from this workspace's GLM-OCR bundle (tt_glmocr/server/worker.py, itself from the Qwen3-ASR and
# Qwen3-TTS bundles; Apache-2.0).
"""The device worker of the HTTP server: ONE thread owns the model (every device call, from the build to the
shutdown, runs on it) and requests wait in a bounded FIFO (batch 1). The chip itself is opened and closed by the
server's lifespan on the main thread (see app.py).

* :meth:`DeviceWorker.submit` queues a job; more than ``depth`` waiting jobs -> :class:`QueueFull` (HTTP 429).
* A job that waited longer than ``timeout_s`` when the worker reaches it is dropped with :class:`QueueTimeout`
  (HTTP 503); the HTTP handler also stops waiting for it after ``timeout_s`` and cancels it.
* A job reports through ``on_event(kind, payload)`` (called ON THE WORKER THREAD; the server forwards to the event
  loop): ``("started", wait_s)``, any number of job-specific events (text deltas), then ``("done", result)`` or
  ``("error", exception)``. ``job.cancel`` is a ``threading.Event`` the job polls (the client went away).

Standard library only.
"""
from __future__ import annotations

import concurrent.futures
import logging
import queue
import threading
import time
from typing import Any, Callable, Optional

__all__ = ["DeviceWorker", "Job", "QueueFull", "QueueTimeout", "ShuttingDown"]

LOG = logging.getLogger("tt_dsocr.server.worker")


class QueueFull(RuntimeError):
    pass


class QueueTimeout(RuntimeError):
    pass


class ShuttingDown(RuntimeError):
    pass


class Job:
    def __init__(self, fn: Callable[["Job"], Any], on_event: Optional[Callable[[str, Any], None]], kind: str):
        self.fn = fn
        self.on_event = on_event
        self.kind = kind
        self.cancel = threading.Event()
        self.future: "concurrent.futures.Future[Any]" = concurrent.futures.Future()
        self.enqueued = time.monotonic()
        self.started: Optional[float] = None
        self.state = "queued"

    def emit(self, kind: str, payload: Any = None) -> None:
        if self.on_event is not None:
            try:
                self.on_event(kind, payload)
            except Exception:  # noqa: BLE001 -- the receiver went away (event loop closed)
                LOG.debug("event %s dropped", kind)

    def _finish(self, kind: str, payload: Any) -> None:
        self.state = kind
        self.emit(kind, payload)
        if self.future.done():
            return
        if kind == "done":
            self.future.set_result(payload)
        else:
            self.future.set_exception(payload)


class DeviceWorker:
    def __init__(self, depth: int, timeout_s: float, name: str = "dsocr-device"):
        self.depth = int(depth)
        self.timeout_s = float(timeout_s)
        self._q: "queue.Queue[Optional[Job]]" = queue.Queue()
        self._lock = threading.Lock()
        self.waiting = 0
        self.running: Optional[Job] = None
        self.completed = 0
        self._closing = False
        self._thread = threading.Thread(target=self._loop, name=name, daemon=True)
        self._thread.start()

    @property
    def alive(self) -> bool:
        return self._thread.is_alive()

    @property
    def thread_id(self) -> Optional[int]:
        return self._thread.ident

    def submit(self, fn: Callable[[Job], Any], *, on_event: Optional[Callable[[str, Any], None]] = None,
               kind: str = "ocr", priority: bool = False) -> Job:
        """Queue ``fn(job)``. ``priority`` jobs (start-up, shutdown) ignore the depth limit."""
        job = Job(fn, on_event, kind)
        with self._lock:
            if self._closing and not priority:
                raise ShuttingDown("the server is shutting down")
            if not priority and self.waiting >= self.depth and (self.running is not None or self.waiting > 0):
                raise QueueFull(f"{self.waiting} request(s) are waiting and one is running (DSOCR_QUEUE_DEPTH="
                                f"{self.depth}); retry later")
            self.waiting += 1
        if priority:
            job.enqueued = float("inf")  # never times out in the queue
        self._q.put(job)
        return job

    def call(self, fn: Callable[[], Any], timeout: Optional[float] = None, kind: str = "call") -> Any:
        """Run ``fn()`` on the worker thread and return its result (blocking)."""
        return self.submit(lambda _job: fn(), kind=kind, priority=True).future.result(timeout)

    def _loop(self) -> None:
        while True:
            job = self._q.get()
            if job is None:
                break
            with self._lock:
                self.waiting -= 1
                self.running = job
            outcome: tuple = ("error", RuntimeError("the job did not run"))
            try:
                waited = time.monotonic() - job.enqueued if job.enqueued != float("inf") else 0.0
                if job.cancel.is_set():
                    outcome = ("error", QueueTimeout("cancelled while waiting in the queue"))
                elif self._closing and job.kind not in ("call", "close"):
                    outcome = ("error", ShuttingDown("the server is shutting down"))
                elif waited > self.timeout_s:
                    outcome = ("error", QueueTimeout(f"waited {waited:.1f} s in the queue (DSOCR_QUEUE_TIMEOUT_S="
                                                     f"{self.timeout_s:g})"))
                else:
                    job.started = time.monotonic()
                    job.state = "running"
                    job.emit("started", waited)
                    try:
                        outcome = ("done", job.fn(job))
                    except BaseException as e:  # noqa: BLE001 -- reported to the waiting handler
                        outcome = ("error", e)
            finally:
                # free the slot BEFORE the waiter learns the outcome: a request sent right after sees an idle worker
                with self._lock:
                    self.running = None
                    self.completed += 1
                job._finish(*outcome)

    def status(self) -> dict:
        r = self.running
        return {"waiting": self.waiting, "running": None if r is None else r.kind, "depth": self.depth,
                "timeout_s": self.timeout_s, "completed": self.completed}

    def shutdown(self, close_fn: Optional[Callable[[], Any]] = None, wait_s: float = 100.0) -> None:
        """Refuse new jobs, cancel the queued ones and the running one, run ``close_fn`` on the worker, stop."""
        with self._lock:
            self._closing = True
            r = self.running
        if r is not None:
            r.cancel.set()
        drained = []
        while True:
            try:
                j = self._q.get_nowait()
            except queue.Empty:
                break
            if j is not None:
                drained.append(j)
        for j in drained:
            with self._lock:
                self.waiting -= 1
            j._finish("error", ShuttingDown("the server is shutting down"))
        if close_fn is not None:
            job = Job(lambda _j: close_fn(), None, "close")
            job.enqueued = float("inf")
            with self._lock:
                self.waiting += 1
            self._q.put(job)
            try:
                job.future.result(wait_s)
            except concurrent.futures.TimeoutError:
                LOG.error("closing the model did not finish within %.0f s", wait_s)
            except Exception as e:  # noqa: BLE001
                LOG.error("closing the model failed: %s: %s", type(e).__name__, e)
        self._q.put(None)
        self._thread.join(timeout=10.0)