跳转至

API Reference

公开 API

blendjob

Reusable local HTTP Job Server for Blender add-ons.

JobClient

Dependency-free HTTP client for a local :class:JobServer.

源代码位于: src\blendjob\client.py
 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
class JobClient:
    """Dependency-free HTTP client for a local :class:`JobServer`."""

    def __init__(self, host, port, *, timeout=2.0):
        self.base_url = f"http://{host}:{int(port)}"
        self.timeout = timeout
        self.opener = build_opener(ProxyHandler({}))

    def request(self, method, path, payload=None, timeout=None):
        data = None
        headers = {}
        if payload is not None:
            data = json.dumps(payload).encode("utf-8")
            headers["Content-Type"] = "application/json"
        request = Request(
            f"{self.base_url}{path}",
            data=data,
            headers=headers,
            method=method,
        )
        try:
            with self.opener.open(
                request,
                timeout=self.timeout if timeout is None else timeout,
            ) as response:
                return json.loads(response.read().decode("utf-8"))
        except HTTPError as error:
            try:
                detail = json.loads(error.read().decode("utf-8")).get("detail")
            except (json.JSONDecodeError, UnicodeDecodeError):
                detail = None
            raise RuntimeError(detail or f"Job Server returned HTTP {error.code}")
        except (OSError, URLError) as error:
            raise RuntimeError(f"Unable to reach Job Server: {error}")

    def health(self):
        return self.request("GET", "/health")

    def submit(self, job_type, parameters):
        return self.request(
            "POST",
            "/jobs",
            {"job_type": str(job_type), "parameters": dict(parameters)},
        )

    def status(self, job_id):
        return self.request("GET", f"/jobs/{job_id}")

    def cancel(self, job_id):
        return self.request("DELETE", f"/jobs/{job_id}")

    def resources(self):
        return self.request("GET", "/resources")

    def resource(self, name):
        return self.request("GET", f"/resources/{name}")

    def clear_resource(self, name):
        return self.request("POST", f"/resources/{name}/clear")

    def shutdown(self):
        return self.request("POST", "/shutdown")

JobResult dataclass

Successful Job value and files returned to a Blender Operator.

源代码位于: src\blendjob\client.py
 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
@dataclass(frozen=True)
class JobResult:
    """Successful Job value and files returned to a Blender Operator."""

    job_id: str
    directory: Path
    value: object
    status: dict

    @classmethod
    def from_status(cls, status):
        return cls(
            job_id=str(status.get("job_id", "")),
            directory=Path(status["directory"]),
            value=status.get("result"),
            status=dict(status),
        )

    def file(self, name):
        if not isinstance(self.value, dict):
            raise RuntimeError("Job result does not contain named files")
        try:
            relative = self.value[name]
        except KeyError:
            raise RuntimeError(f"Job result does not contain file: {name}") from None
        root = self.directory.resolve()
        path = (root / str(relative)).resolve()
        if path != root and root not in path.parents:
            raise RuntimeError(f"Job result file escapes its directory: {relative}")
        if not path.is_file():
            raise RuntimeError(f"Job result file does not exist: {path}")
        return path

ServerController

Own a dedicated local JobServer process and its HTTP connection.

源代码位于: src\blendjob\controller.py
 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
class ServerController:
    """Own a dedicated local JobServer process and its HTTP connection."""

    def __init__(
        self,
        command_factory,
        *,
        cwd_factory,
        log_path_factory,
        host="127.0.0.1",
        creationflags=0,
    ):
        self.command_factory = command_factory
        self.cwd_factory = cwd_factory
        self.log_path_factory = log_path_factory
        self.host = host
        self.creationflags = creationflags
        self.connection = None
        self.process = None
        self.log_file = None
        self.auto_start = False
        self.snapshot = {"state": "STOPPED", "message": "Stopped"}

    def start(self):
        if self.process is not None and self.process.poll() is None:
            return self.connection
        self._close_process()
        port = self._available_port()
        instance_id = uuid.uuid4().hex
        log_path = self.log_path_factory()
        log_path.parent.mkdir(parents=True, exist_ok=True)
        self.log_file = log_path.open("a", encoding="utf-8")
        command = self.command_factory(port, instance_id)
        try:
            self.process = subprocess.Popen(
                command,
                stdout=self.log_file,
                stderr=subprocess.STDOUT,
                cwd=self.cwd_factory(),
                creationflags=self.creationflags,
            )
        except OSError:
            self.log_file.close()
            self.log_file = None
            raise
        client = JobClient(self.host, port)
        self.connection = ServerConnection(
            port,
            self.process.pid,
            instance_id,
            client,
        )
        self.snapshot = {"state": "STARTING", "message": "Starting", "port": port}
        return self.connection

    def health(self, timeout=0.3):
        if self.connection is None:
            raise RuntimeError("Server is not running")
        health = self.connection.client.request("GET", "/health", timeout=timeout)
        if health.get("instance_id") != self.connection.instance_id:
            raise RuntimeError("Server instance does not match")
        state = "BUSY" if health.get("busy") else "READY"
        self.snapshot = {
            **health,
            "state": state,
            "message": "Busy" if state == "BUSY" else "Ready",
            "port": self.connection.port,
        }
        return health

    def ensure(self, timeout=60.0):
        self.auto_start = True
        deadline = time.monotonic() + timeout
        while time.monotonic() < deadline:
            try:
                self.health(timeout=0.5)
                return self.connection
            except RuntimeError:
                self._close_finished_process()
            if self.process is None:
                self.start()
            time.sleep(0.05)
        raise RuntimeError(f"Server did not become ready; log: {self.log_path_factory()}")

    def enable(self):
        self.auto_start = True
        try:
            self.health(timeout=0.2)
        except RuntimeError:
            self.start()
        return self.connection

    def stop(self, timeout=10.0):
        self.auto_start = False
        if self.connection is not None:
            try:
                self.connection.client.shutdown()
            except RuntimeError:
                pass
        deadline = time.monotonic() + timeout
        while self.process is not None and self.process.poll() is None:
            if time.monotonic() >= deadline:
                self._close_process(terminate=True)
                break
            time.sleep(0.05)
        self._close_process()
        self.connection = None
        self.snapshot = {"state": "STOPPED", "message": "Stopped"}

    def restart(self):
        self.stop()
        self.auto_start = True
        return self.start()

    def submit(self, job_type, parameters):
        return self.ensure().client.submit(job_type, parameters)

    def request(
        self,
        job_type,
        parameters,
        *,
        response=None,
        progress=None,
        cancel_check=None,
        poll_interval=0.25,
    ):
        """Submit one Job and return its response after polling to completion."""
        submitted = self.submit(job_type, parameters)
        job_id = submitted["job_id"]
        directory = submitted["directory"]
        cancel_requested = False
        try:
            while True:
                if (
                    not cancel_requested
                    and cancel_check is not None
                    and cancel_check()
                ):
                    self.cancel(job_id)
                    cancel_requested = True
                status = self.status(job_id)
                if progress is not None:
                    progress({"job_id": job_id, "directory": directory, **status})
                state = status.get("state")
                if state == "succeeded":
                    result = JobResult.from_status(
                        {"job_id": job_id, "directory": directory, **status}
                    )
                    if response is not None:
                        response(result)
                    return result
                if state == "cancelled":
                    raise RuntimeError("Server request was cancelled")
                if state == "failed":
                    raise RuntimeError(status.get("error") or "Server request failed")
                time.sleep(max(float(poll_interval), 0.01))
        finally:
            self.mark_job_complete(job_id)

    def status(self, job_id):
        return self.ensure().client.status(job_id)

    def cancel(self, job_id):
        return self.ensure().client.cancel(job_id)

    def resource(self, name):
        return self.ensure().client.resource(name)

    def clear_resource(self, name):
        return self.ensure().client.clear_resource(name)

    def detach(self):
        self.auto_start = False
        self.connection = None
        self._close_process(terminate=True)
        self.snapshot = {"state": "STOPPED", "message": "Stopped"}

    def poll(self, *, available=True):
        if not available:
            self.snapshot = {"state": "UNAVAILABLE", "message": "Environment is not installed"}
            return 2.0
        try:
            self.health(timeout=0.5)
            return 5.0
        except RuntimeError as error:
            self._close_finished_process()
            if not self.auto_start:
                self.snapshot = {"state": "STOPPED", "message": "Stopped"}
                return 2.0
            try:
                self.start()
            except OSError as start_error:
                self.snapshot = {"state": "ERROR", "message": str(start_error)}
                return 2.0
            self.snapshot = {"state": "STARTING", "message": "Starting"}
            return 1.0

    def mark_job_complete(self, job_id):
        active = self.snapshot.get("active_job")
        if active and active.get("job_id") != job_id:
            return
        if self.snapshot.get("state") == "BUSY":
            self.snapshot = {
                **self.snapshot,
                "busy": False,
                "active_job": None,
                "state": "READY",
                "message": "Ready",
            }

    def _available_port(self):
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener:
            listener.bind((self.host, 0))
            return listener.getsockname()[1]

    def _close_finished_process(self):
        if self.process is not None and self.process.poll() is not None:
            self._close_process()
            self.connection = None

    def _close_process(self, terminate=False):
        process = self.process
        self.process = None
        if process is not None and terminate and process.poll() is None:
            process.terminate()
            try:
                process.wait(timeout=3.0)
            except subprocess.TimeoutExpired:
                process.kill()
                process.wait(timeout=3.0)
        if self.log_file is not None:
            self.log_file.close()
            self.log_file = None

request(job_type, parameters, *, response=None, progress=None, cancel_check=None, poll_interval=0.25)

Submit one Job and return its response after polling to completion.

源代码位于: src\blendjob\controller.py
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
def request(
    self,
    job_type,
    parameters,
    *,
    response=None,
    progress=None,
    cancel_check=None,
    poll_interval=0.25,
):
    """Submit one Job and return its response after polling to completion."""
    submitted = self.submit(job_type, parameters)
    job_id = submitted["job_id"]
    directory = submitted["directory"]
    cancel_requested = False
    try:
        while True:
            if (
                not cancel_requested
                and cancel_check is not None
                and cancel_check()
            ):
                self.cancel(job_id)
                cancel_requested = True
            status = self.status(job_id)
            if progress is not None:
                progress({"job_id": job_id, "directory": directory, **status})
            state = status.get("state")
            if state == "succeeded":
                result = JobResult.from_status(
                    {"job_id": job_id, "directory": directory, **status}
                )
                if response is not None:
                    response(result)
                return result
            if state == "cancelled":
                raise RuntimeError("Server request was cancelled")
            if state == "failed":
                raise RuntimeError(status.get("error") or "Server request failed")
            time.sleep(max(float(poll_interval), 0.01))
    finally:
        self.mark_job_complete(job_id)

JobOperatorBase

Blender mixin that turns one Operator into a complete remote Job.

源代码位于: src\blendjob\operator.py
 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
class JobOperatorBase:
    """Blender mixin that turns one Operator into a complete remote Job."""

    bl_options = {"INTERNAL"}
    poll_interval = 0.25
    starting_message = "Starting task"
    job_runtime = None
    job_type = ""

    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        annotations = {}
        for base in reversed(cls.__mro__[1:]):
            annotations.update(getattr(base, "__annotations__", {}))
        annotations.update(cls.__dict__.get("__annotations__", {}))
        if annotations:
            cls.__annotations__ = annotations

    def request(self, _context):
        """Return the complete JSON parameters submitted to the Server."""
        return operator_properties(self)

    def response(self, _context, _result):
        """Apply an optional successful result on Blender's main thread."""

    def cleanup(self):
        """Release invocation resources after every terminal outcome."""

    def controller(self, runtime):
        """Return the operation controller used by this invocation."""
        return runtime.server

    def execute(self, context):
        runtime = self._runtime()
        if runtime.active_job is not None:
            self.report({"WARNING"}, "Another task is running")
            return {"CANCELLED"}
        if not self.job_type:
            self.report({"ERROR"}, "Set job_type on the Job Operator")
            return {"CANCELLED"}
        try:
            parameters = self.request(context)
            if not isinstance(parameters, dict):
                raise TypeError("request(context) must return a dict")
            json.dumps(parameters)
            controller = self.controller(runtime)
        except (OSError, RuntimeError, TypeError, ValueError) as error:
            self.report({"ERROR"}, str(error))
            return {"CANCELLED"}

        job = JobOperatorState(runtime, self, controller)
        runtime.begin_job(job)
        if hasattr(context.window_manager, "progress_begin"):
            context.window_manager.progress_begin(0, 100)
        runtime.update_ui(context, 0.0, self.starting_message)
        self._timer = context.window_manager.event_timer_add(
            self.poll_interval,
            window=context.window,
        )
        context.window_manager.modal_handler_add(self)
        runtime.redraw_ui(context, force=True)
        job.start_thread = threading.Thread(
            target=self._submit_job,
            args=(job, parameters),
            name="BlendJobSubmit",
            daemon=True,
        )
        job.start_thread.start()
        return {"RUNNING_MODAL"}

    def _submit_job(self, job, parameters):
        if job.cancelled:
            job.started = True
            return
        try:
            submitted = job.controller.submit(self.job_type, parameters)
            job.job_id = submitted["job_id"]
            job.directory = Path(submitted["directory"])
            job.started = True
            if job.cancelled:
                job.controller.cancel(job.job_id)
        except (KeyError, OSError, RuntimeError, TypeError) as error:
            job.start_error = str(error)

    def modal(self, context, event):
        runtime = self._runtime()
        if event.type == "ESC":
            runtime.cancel_active()
        if event.type != "TIMER":
            return {"PASS_THROUGH"}

        job = runtime.active_job
        if job is None:
            self.remove_job_timer(context)
            return {"CANCELLED"}
        if job.start_error:
            self.report({"ERROR"}, f"Unable to start task: {job.start_error}")
            return self._close(context, job, "Task failed to start", cancelled=True)
        if not job.started:
            return {"RUNNING_MODAL"}
        if job.cancelled and not job.job_id:
            return self._close(context, job, "Task cancelled", cancelled=True)

        try:
            status = job.controller.status(job.job_id)
        except RuntimeError as error:
            return self._finish_failure(context, job, error)
        self.update_from_job_status(context, job, status)
        state = status.get("state")
        if state == "succeeded":
            return self._finish_success(context, job, status)
        if state in {"failed", "cancelled"}:
            if job.cancelled or state == "cancelled":
                return self._close(context, job, "Task cancelled", cancelled=True)
            return self._finish_failure(
                context,
                job,
                status.get("error") or "Server task failed",
            )
        return {"RUNNING_MODAL"}

    def _finish_success(self, context, job, status):
        try:
            complete_status = {
                "job_id": job.job_id,
                "directory": str(job.directory),
                **status,
            }
            message = self.response(
                context,
                JobResult.from_status(complete_status),
            )
        except (OSError, RuntimeError, TypeError, ValueError) as error:
            return self._finish_failure(context, job, error)
        return self._close(
            context,
            job,
            message or status.get("message") or "Task complete",
            cancelled=False,
        )

    def _finish_failure(self, context, job, error):
        self.report({"ERROR"}, str(error))
        return self._close(context, job, "Task failed", cancelled=True)

    def _close(self, context, job, message, *, cancelled):
        self.remove_job_timer(context)
        if hasattr(context.window_manager, "progress_end"):
            context.window_manager.progress_end()
        job.runtime.finish_job(job)
        job.runtime.update_ui(context, 0.0 if cancelled else 1.0, message)
        job.runtime.redraw_ui(context, force=True)
        return {"CANCELLED"} if cancelled else {"FINISHED"}

    def update_from_job_status(self, context, job, status):
        reported = min(max(float(status.get("progress", job.progress)), 0.0), 1.0)
        stage = status.get("stage")
        if stage is not None and stage != job.progress_stage:
            job.progress_stage = stage
            job.progress = reported
        else:
            job.progress = max(job.progress, reported)
        message = self.format_job_status(status, self.starting_message)
        job.runtime.update_ui(context, job.progress, message)
        job.runtime.redraw_ui(context, force=True)

    def format_job_status(self, status, fallback):
        message = status.get("message")
        stage = status.get("stage")
        stages = status.get("stages")
        stage_label = status.get("stage_label")
        if stage and stages:
            prefix = f"{stage}/{stages}"
            normalized = str(message or "").strip()
            if normalized and normalized.lower() != str(stage_label or "").lower():
                return f"{prefix} {normalized}"
            return f"{prefix} {stage_label}" if stage_label else prefix
        return str(message or stage_label or fallback).strip()

    def remove_job_timer(self, context):
        timer = getattr(self, "_timer", None)
        if timer is None:
            return
        context.window_manager.event_timer_remove(timer)
        self._timer = None

    def cancel(self, context):
        runtime = self._runtime()
        job = runtime.active_job
        runtime.cancel_active()
        self.remove_job_timer(context)
        if job is None:
            return
        if hasattr(context.window_manager, "progress_end"):
            context.window_manager.progress_end()
        runtime.finish_job(job)
        runtime.update_ui(context, 0.0, "Task cancelled")
        runtime.redraw_ui(context, force=True)

    def _runtime(self):
        if self.job_runtime is None:
            raise RuntimeError("Use JobRuntime.JobOperatorBase")
        return self.job_runtime

request(_context)

Return the complete JSON parameters submitted to the Server.

源代码位于: src\blendjob\operator.py
71
72
73
def request(self, _context):
    """Return the complete JSON parameters submitted to the Server."""
    return operator_properties(self)

response(_context, _result)

Apply an optional successful result on Blender's main thread.

源代码位于: src\blendjob\operator.py
75
76
def response(self, _context, _result):
    """Apply an optional successful result on Blender's main thread."""

cleanup()

Release invocation resources after every terminal outcome.

源代码位于: src\blendjob\operator.py
78
79
def cleanup(self):
    """Release invocation resources after every terminal outcome."""

controller(runtime)

Return the operation controller used by this invocation.

源代码位于: src\blendjob\operator.py
81
82
83
def controller(self, runtime):
    """Return the operation controller used by this invocation."""
    return runtime.server

JobOperatorState dataclass

Internal state for one modal Job Operator invocation.

源代码位于: src\blendjob\operator.py
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@dataclass
class JobOperatorState:
    """Internal state for one modal Job Operator invocation."""

    runtime: object
    operator: object
    controller: object
    job_id: str = ""
    directory: Path | None = None
    started: bool = False
    cancelled: bool = False
    start_error: str = ""
    start_thread: threading.Thread | None = None
    progress_stage: int | None = None
    progress: float = 0.0

JobRuntime

Own one add-on's Storage Root, Environment, Server and Blender UI.

源代码位于: src\blendjob\runtime.py
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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
class JobRuntime:
    """Own one add-on's Storage Root, Environment, Server and Blender UI."""

    def __init__(
        self,
        server_entrypoint,
        *,
        entrypoint_root=None,
        storage_root,
        environment,
        namespace,
        post_install=None,
    ):
        self.server_entrypoint = normalized_entrypoint(
            server_entrypoint,
            root=entrypoint_root,
        )
        self.storage_root_factory = storage_root
        self.environment = normalized_environment(environment)
        self.environment_hash = environment_digest(self.environment)
        if post_install is not None and not callable(post_install):
            raise TypeError("post_install must be callable")
        self.post_install = post_install
        if not isinstance(namespace, str) or not namespace.strip():
            raise ValueError("namespace must be a non-empty string")
        self.namespace = namespace.strip()
        self.active_job = None
        self.progress = 0.0
        self.message = "Ready"
        self._operator_base = None
        self._operator_classes = None
        self._timer_registered = False
        self._registered = False
        self._status_bar_draw = self._create_status_bar_draw()
        self._request_progress = None
        self._request_cancel_check = None
        self._environment_controller = EnvironmentController(self)
        self.server = ServerController(
            self._server_command,
            cwd_factory=self.storage_root,
            log_path_factory=self.server_log_path,
            creationflags=windows_creation_flags(),
        )
        self.JobOperatorBase = self.operator_base()

    def storage_root(self):
        configured = (
            self.storage_root_factory()
            if callable(self.storage_root_factory)
            else self.storage_root_factory
        )
        root = Path(configured).expanduser().resolve()
        root.mkdir(parents=True, exist_ok=True)
        return root

    def environment_directory(self):
        return self.storage_root() / ".venv"

    def environment_python(self):
        directory = self.environment_directory()
        if os.name == "nt":
            return directory / "Scripts" / "python.exe"
        return directory / "bin" / "python"

    def environment_manifest_path(self):
        return self.storage_root() / "manifest.json"

    def environment_config_path(self):
        return self.storage_root() / "environment.json"

    def install_status_path(self):
        return self.storage_root() / "install-status.json"

    def install_log_path(self):
        return self.storage_root() / "install.log"

    def server_log_path(self):
        return self.storage_root() / "server.log"

    def environment_manifest(self):
        try:
            value = json.loads(
                self.environment_manifest_path().read_text(encoding="utf-8")
            )
        except (FileNotFoundError, json.JSONDecodeError, OSError):
            return {}
        return value if isinstance(value, dict) else {}

    def environment_ready(self):
        return (
            self.environment_python().is_file()
            and self.environment_manifest().get("environment_hash")
            == self.environment_hash
        )

    def write_environment_config(self):
        path = self.environment_config_path()
        path.write_text(
            json.dumps(self.environment, indent=2),
            encoding="utf-8",
        )
        return path

    def install_command(self):
        installer = Path(__file__).with_name("installer") / "environment.py"
        config = self.write_environment_config()
        return [
            sys.executable,
            str(installer),
            "--storage-root",
            str(self.storage_root()),
            "--config",
            str(config),
            "--status",
            str(self.install_status_path()),
            "--stages",
            "1",
        ]

    def request(self, job_type, parameters, response=None):
        """Directly request one Server Job and return its JobResult."""
        if self._request_cancel_check is not None and self._request_cancel_check():
            raise RuntimeError("Server request was cancelled")
        return self.server.request(
            job_type,
            parameters,
            response=response,
            progress=self._request_progress,
            cancel_check=self._request_cancel_check,
        )

    def operator_base(self):
        if self._operator_base is not None:
            return self._operator_base
        runtime = self

        class BoundJobOperator(JobOperatorBase):
            job_runtime = runtime

        BoundJobOperator.__name__ = "JobOperatorBase"
        self._operator_base = BoundJobOperator
        return BoundJobOperator

    def operator_classes(self):
        if self._operator_classes is not None:
            return self._operator_classes
        import bpy

        runtime = self
        operator_base = self.JobOperatorBase

        class InstallEnvironment(operator_base, bpy.types.Operator):
            bl_idname = f"{runtime.namespace}.install_environment"
            bl_label = "Install Environment"
            job_type = "install-environment"
            starting_message = "Starting Environment installation"

            def request(self, _context):
                if not bpy.app.online_access:
                    raise RuntimeError(
                        "Online Access is disabled in Blender Preferences"
                    )
                return {}

            def controller(self, _runtime):
                runtime.server.stop()
                return runtime._environment_controller

        class CancelJob(bpy.types.Operator):
            bl_idname = f"{runtime.namespace}.cancel_job"
            bl_label = "Cancel Job"

            @classmethod
            def poll(cls, _context):
                return runtime.active_job is not None

            def execute(self, _context):
                runtime.cancel_active()
                return {"FINISHED"}

        class StartServer(bpy.types.Operator):
            bl_idname = f"{runtime.namespace}.start_server"
            bl_label = "Start Server"

            def execute(self, _context):
                try:
                    runtime.server.enable()
                except (OSError, RuntimeError) as error:
                    self.report({"ERROR"}, str(error))
                    return {"CANCELLED"}
                return {"FINISHED"}

        class StopServer(bpy.types.Operator):
            bl_idname = f"{runtime.namespace}.stop_server"
            bl_label = "Stop Server"

            def execute(self, _context):
                runtime.server.stop()
                runtime.redraw_ui()
                return {"FINISHED"}

        class RestartServer(bpy.types.Operator):
            bl_idname = f"{runtime.namespace}.restart_server"
            bl_label = "Restart Server"

            def execute(self, _context):
                try:
                    runtime.server.restart()
                except (OSError, RuntimeError) as error:
                    self.report({"ERROR"}, str(error))
                    return {"CANCELLED"}
                return {"FINISHED"}

        class OpenServerLog(bpy.types.Operator):
            bl_idname = f"{runtime.namespace}.open_server_log"
            bl_label = "Open Server Log"

            def execute(self, _context):
                path = runtime.server_log_path()
                target = path if path.is_file() else path.parent
                result = bpy.ops.wm.path_open(filepath=str(target))
                if "FINISHED" not in result:
                    self.report({"ERROR"}, "Unable to open the Server log")
                    return {"CANCELLED"}
                return {"FINISHED"}

        self._operator_classes = (
            InstallEnvironment,
            CancelJob,
            StartServer,
            StopServer,
            RestartServer,
            OpenServerLog,
        )
        return self._operator_classes

    def register(self):
        if self._registered:
            return
        import bpy

        for class_type in self.operator_classes():
            bpy.utils.register_class(class_type)
        bpy.types.STATUSBAR_HT_header.append(self._status_bar_draw)
        self._registered = True
        self.enable()

    def unregister(self):
        if not self._registered:
            return
        import bpy

        self.disable()
        bpy.types.STATUSBAR_HT_header.remove(self._status_bar_draw)
        for class_type in reversed(self.operator_classes()):
            bpy.utils.unregister_class(class_type)
        self._registered = False

    def begin_job(self, job):
        if self.active_job is not None:
            raise RuntimeError("Another task is running")
        self.active_job = job

    def finish_job(self, job):
        if job.job_id:
            job.controller.mark_job_complete(job.job_id)
        try:
            job.operator.cleanup()
        finally:
            if self.active_job is job:
                self.active_job = None

    def cancel_active(self):
        job = self.active_job
        if job is None:
            return
        job.cancelled = True
        if not job.started or not job.job_id:
            return
        try:
            job.controller.cancel(job.job_id)
        except RuntimeError:
            pass

    def close_active(self):
        job = self.active_job
        if job is not None:
            self.finish_job(job)

    def update_ui(self, context, progress, message):
        self.progress = min(max(float(progress), 0.0), 1.0)
        self.message = str(message)
        window_manager = getattr(context, "window_manager", None)
        if window_manager is not None and hasattr(
            window_manager, "progress_update"
        ):
            window_manager.progress_update(int(self.progress * 100))
        self.redraw_ui(context)

    def redraw_ui(self, context=None, force=False):
        try:
            import bpy
        except ModuleNotFoundError:
            return
        context = context or bpy.context
        window_manager = getattr(context, "window_manager", None)
        for window in getattr(window_manager, "windows", ()):
            screen = getattr(window, "screen", None)
            for area in getattr(screen, "areas", ()):
                if area.type in {"STATUSBAR", "VIEW_3D", "PREFERENCES"}:
                    area.tag_redraw()
                    for region in getattr(area, "regions", ()):
                        region.tag_redraw()
        if not force:
            return
        workspace = getattr(context, "workspace", None)
        if workspace is not None:
            try:
                workspace.status_text_set_internal(None)
            except (AttributeError, RuntimeError, TypeError):
                pass

    def server_status(self):
        return dict(self.server.snapshot)

    def server_busy(self):
        return self.active_job is not None or self.server.snapshot.get(
            "state"
        ) == "BUSY"

    def resource(self, name):
        return self.server.resource(name)

    def clear_resource(self, name):
        return self.server.clear_resource(name)

    def enable(self):
        try:
            import bpy
        except ModuleNotFoundError:
            return
        timers = getattr(bpy.app, "timers", None)
        if timers is None or timers.is_registered(self._poll_server):
            return
        timers.register(self._poll_server, first_interval=1.0, persistent=True)
        self._timer_registered = True

    def disable(self):
        self.cancel_active()
        self.close_active()
        try:
            import bpy
        except ModuleNotFoundError:
            bpy = None
        timers = getattr(getattr(bpy, "app", None), "timers", None)
        if timers is not None and timers.is_registered(self._poll_server):
            timers.unregister(self._poll_server)
        self._timer_registered = False
        self.server.detach()

    def _poll_server(self):
        interval = self.server.poll(available=self.environment_ready())
        self.redraw_ui()
        return interval

    def _draw_status_bar(self, owner, _context):
        if self.active_job is None:
            return
        row = owner.layout.row(align=True)
        progress_row = row.row(align=True)
        progress_row.ui_units_x = 18.0
        progress_row.progress(
            factor=self.progress,
            type="BAR",
            text=self.message,
        )
        row.operator(
            f"{self.namespace}.cancel_job",
            text="",
            icon="X",
        )

    def _create_status_bar_draw(self):
        runtime = self

        def draw_status_bar(owner, context):
            runtime._draw_status_bar(owner, context)

        return draw_status_bar

    def _server_command(self, port, instance_id):
        launcher = Path(__file__).with_name("launcher") / "runner.py"
        return [
            str(self.environment_python()),
            "-u",
            str(launcher),
            "--entrypoint",
            self.server_entrypoint,
            "--storage-root",
            str(self.storage_root()),
            "--host",
            "127.0.0.1",
            "--port",
            str(port),
            "--instance-id",
            instance_id,
            "--parent-pid",
            str(os.getpid()),
        ]

request(job_type, parameters, response=None)

Directly request one Server Job and return its JobResult.

源代码位于: src\blendjob\runtime.py
292
293
294
295
296
297
298
299
300
301
302
def request(self, job_type, parameters, response=None):
    """Directly request one Server Job and return its JobResult."""
    if self._request_cancel_check is not None and self._request_cancel_check():
        raise RuntimeError("Server request was cancelled")
    return self.server.request(
        job_type,
        parameters,
        response=response,
        progress=self._request_progress,
        cancel_check=self._request_cancel_check,
    )

JobCancelled

Bases: RuntimeError

Raised by a handler when its job has been cancelled.

源代码位于: src\blendjob\server.py
14
15
class JobCancelled(RuntimeError):
    """Raised by a handler when its job has been cancelled."""

JobContext

Mutable state and cancellation API passed to a registered job handler.

源代码位于: src\blendjob\server.py
 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
class JobContext:
    """Mutable state and cancellation API passed to a registered job handler."""

    def __init__(
        self,
        job_id,
        job_type,
        parameters,
        resources,
        storage_root,
        directory,
    ):
        self.job_id = job_id
        self.job_type = job_type
        self.parameters = parameters
        self.storage_root = Path(storage_root)
        self.directory = Path(directory)
        self._resources = resources
        self._lock = threading.Lock()
        self._cancel_requested = False
        self._status = {
            "job_id": job_id,
            "job_type": job_type,
            "state": "queued",
            "progress": 0.0,
            "message": "Task queued",
            "directory": str(self.directory),
        }

    def _update(self, progress, message, error=None, state=None, **details):
        if state is None:
            if error:
                state = "failed"
            elif progress >= 1.0:
                state = "succeeded"
            else:
                state = "running"
        snapshot = {
            "job_id": self.job_id,
            "job_type": self.job_type,
            "state": state,
            "progress": min(max(float(progress), 0.0), 1.0),
            "message": str(message),
            "directory": str(self.directory),
            **{key: value for key, value in details.items() if value is not None},
        }
        if error:
            snapshot["error"] = str(error)
        with self._lock:
            self._status = snapshot

    def progress(self, progress, message, **details):
        """Publish running progress from a Job handler."""
        self._update(progress, message, state="running", **details)

    def succeed(self, result=None, message="Task complete"):
        """Publish a successful terminal result."""
        details = {"result": result} if result is not None else {}
        self._update(1.0, message, state="succeeded", **details)

    def snapshot(self):
        with self._lock:
            return dict(self._status)

    def request_cancel(self):
        with self._lock:
            if self._status["state"] in TERMINAL_STATES:
                return False
            self._cancel_requested = True
            self._status = {
                **self._status,
                "state": "cancelling",
                "message": "Cancelling task",
            }
            return True

    def is_cancelled(self):
        with self._lock:
            return self._cancel_requested

    def check_cancelled(self):
        if self.is_cancelled():
            raise JobCancelled("Task cancelled")

    def resource(self, name):
        """Return a shared resource registered on the owning JobServer."""
        try:
            return self._resources[name]
        except KeyError:
            raise KeyError(f"Unknown Server Resource: {name}") from None

progress(progress, message, **details)

Publish running progress from a Job handler.

源代码位于: src\blendjob\server.py
69
70
71
def progress(self, progress, message, **details):
    """Publish running progress from a Job handler."""
    self._update(progress, message, state="running", **details)

succeed(result=None, message='Task complete')

Publish a successful terminal result.

源代码位于: src\blendjob\server.py
73
74
75
76
def succeed(self, result=None, message="Task complete"):
    """Publish a successful terminal result."""
    details = {"result": result} if result is not None else {}
    self._update(1.0, message, state="succeeded", **details)

resource(name)

Return a shared resource registered on the owning JobServer.

源代码位于: src\blendjob\server.py
102
103
104
105
106
107
def resource(self, name):
    """Return a shared resource registered on the owning JobServer."""
    try:
        return self._resources[name]
    except KeyError:
        raise KeyError(f"Unknown Server Resource: {name}") from None

JobServer

Small FastAPI wrapper with decorator-based job registration.

源代码位于: src\blendjob\server.py
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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
class JobServer:
    """Small FastAPI wrapper with decorator-based job registration."""

    def __init__(
        self,
        name,
        *,
        storage_root=None,
        max_job_history=100,
    ):
        self.name = name
        self.max_job_history = max(int(max_job_history), 0)
        self.handlers = {}
        self.resources = {}
        self.resource_factories = {}
        self.jobs = {}
        self.futures = {}
        self.active_job_id = None
        self.lock = threading.Lock()
        self.executor = ThreadPoolExecutor(
            max_workers=1,
            thread_name_prefix="BlendJobWorker",
        )
        self.closed = False
        self.shutdown_event = threading.Event()
        self.started_at = time.time()
        self.storage_root = Path(storage_root) if storage_root is not None else None
        self.jobs_directory = (
            self.storage_root / "jobs" if self.storage_root is not None else None
        )

    def bind(self, storage_root):
        """Bind the Server to the Runtime-owned Storage Root."""
        storage_root = Path(storage_root).resolve()
        if self.storage_root is not None:
            current = self.storage_root.resolve()
            if current != storage_root:
                raise RuntimeError(
                    f"Job Server is already bound to another Storage Root: {current}"
                )
        self.storage_root = storage_root
        self.jobs_directory = storage_root / "jobs"
        for name, factory in tuple(self.resource_factories.items()):
            if name not in self.resources:
                self.resources[name] = factory(self)
        return self

    def add_resource(self, name, resource):
        """Register shared state owned for the full Server lifetime."""
        if not name or "/" in name:
            raise ValueError(f"Invalid resource name: {name}")
        with self.lock:
            if name in self.resources:
                raise ValueError(f"Resource is already registered: {name}")
            self.resources[name] = resource
        return resource

    def resource(self, name):
        """Register a Resource factory initialized after Storage Root binding."""
        def register(factory):
            if not name or "/" in name:
                raise ValueError(f"Invalid resource name: {name}")
            if name in self.resources or name in self.resource_factories:
                raise ValueError(f"Resource is already registered: {name}")
            self.resource_factories[name] = factory
            if self.storage_root is not None:
                self.resources[name] = factory(self)
            return factory

        return register

    def resource_snapshot(self, name):
        try:
            resource = self.resources[name]
        except KeyError:
            raise KeyError(name) from None
        snapshot = getattr(resource, "snapshot", None)
        return snapshot() if snapshot is not None else {}

    def resource_snapshots(self):
        return {
            name: self.resource_snapshot(name)
            for name in tuple(self.resources)
        }

    def clear_resource(self, name):
        """Clear an idle Server Resource without racing a new Job submission."""
        with self.lock:
            if self.active_job_id is not None or self._queued_job_count():
                return False
            try:
                resource = self.resources[name]
            except KeyError:
                raise KeyError(name) from None
            clear = getattr(resource, "clear", None)
            if clear is None:
                raise TypeError(f"Resource cannot be cleared: {name}")
            clear()
            return True

    def close(self):
        with self.lock:
            if self.closed:
                return
            self.closed = True
            self.shutdown_event.set()
        self.executor.shutdown(wait=True, cancel_futures=True)
        for resource in reversed(tuple(self.resources.values())):
            close = getattr(resource, "close", None)
            if close is not None:
                close()

    def job(self, job_type):
        """Register ``handler(context, parameters)`` for a public job type."""
        def register(handler):
            if job_type in self.handlers:
                raise ValueError(f"Job type is already registered: {job_type}")
            self.handlers[job_type] = handler
            return handler

        return register

    def snapshot(self, instance_id):
        with self.lock:
            active = self.jobs.get(self.active_job_id)
            queued_jobs = self._queued_job_count()
            result = {
                "ready": True,
                "server": self.name,
                "instance_id": instance_id,
                "busy": active is not None or queued_jobs > 0,
                "active_job": active.snapshot() if active else None,
                "queued_jobs": queued_jobs,
                "started_at": self.started_at,
                "resources": self.resource_snapshots(),
            }
        return result

    def submit(self, job_type, parameters, *, job_id=None):
        if self.storage_root is None or self.jobs_directory is None:
            raise RuntimeError("Bind the Job Server to a Storage Root before submitting")
        job_id = job_id or uuid.uuid4().hex
        if job_type not in self.handlers:
            raise KeyError(job_type)
        if not job_id or Path(job_id).name != job_id or job_id in {".", ".."}:
            raise ValueError(f"Invalid job id: {job_id}")
        with self.lock:
            if self.closed:
                raise RuntimeError("Job Server is closed")
            if job_id in self.jobs:
                raise ValueError(f"Job id already exists: {job_id}")
            self.jobs_directory.mkdir(parents=True, exist_ok=True)
            directory = self.jobs_directory / job_id
            try:
                directory.mkdir()
            except FileExistsError:
                raise ValueError(f"Job directory already exists: {job_id}") from None
            context = JobContext(
                job_id,
                job_type,
                parameters,
                self.resources,
                self.storage_root,
                directory,
            )
            self.jobs[job_id] = context
            self._prune_jobs()
            self.futures[job_id] = self.executor.submit(self.run, context)
        return context

    def cancel(self, job_id):
        with self.lock:
            context = self.jobs.get(job_id)
            future = self.futures.get(job_id)
            if context is None:
                return None
            if future is not None and future.cancel():
                context.request_cancel()
                context._update(1.0, "Task cancelled", state="cancelled")
                self.futures.pop(job_id, None)
                return context
        return context if context.request_cancel() else None

    def _queued_job_count(self):
        return sum(
            context.snapshot()["state"] == "queued"
            for context in self.jobs.values()
        )

    def _prune_jobs(self):
        completed = [
            identifier
            for identifier, context in self.jobs.items()
            if identifier != self.active_job_id
            and context.snapshot()["state"] in TERMINAL_STATES
        ]
        excess = len(completed) - self.max_job_history
        for identifier in completed[:max(excess, 0)]:
            self.jobs.pop(identifier, None)

    def run(self, context):
        with self.lock:
            if context.snapshot()["state"] in TERMINAL_STATES:
                return
            self.active_job_id = context.job_id
        context._update(0.0, "Server accepted the task", state="running")
        try:
            context.check_cancelled()
            result = self.handlers[context.job_type](
                context,
                context.parameters,
            )
            context.check_cancelled()
            snapshot = context.snapshot()
            if snapshot["state"] not in {"failed", "cancelled"}:
                context.succeed(
                    result,
                    message=snapshot.get("message") or "Task complete",
                )
        except JobCancelled:
            context._update(1.0, "Task cancelled", state="cancelled")
        except Exception as error:
            traceback.print_exc()
            context._update(1.0, "Task failed", error=error, state="failed")
        finally:
            with self.lock:
                if self.active_job_id == context.job_id:
                    self.active_job_id = None
                self.futures.pop(context.job_id, None)

    def create_app(self, instance_id, storage_root=None):
        from fastapi import FastAPI, HTTPException

        if storage_root is not None:
            self.bind(storage_root)
        elif self.storage_root is None:
            raise RuntimeError("Storage Root is required to create the Job Server app")

        @asynccontextmanager
        async def lifespan(_app):
            yield
            self.close()

        app = FastAPI(
            title=self.name,
            docs_url=None,
            redoc_url=None,
            openapi_url=None,
            lifespan=lifespan,
        )
        app.state.job_server = self

        @app.get("/health")
        def health():
            return self.snapshot(instance_id)

        @app.get("/resources")
        def resources():
            return self.resource_snapshots()

        @app.get("/resources/{resource_name}")
        def resource_status(
            resource_name: str,
        ):
            try:
                return self.resource_snapshot(resource_name)
            except KeyError:
                raise HTTPException(status_code=404, detail="Resource was not found")

        @app.post("/resources/{resource_name}/clear")
        def clear_resource(
            resource_name: str,
        ):
            try:
                cleared = self.clear_resource(resource_name)
            except KeyError:
                raise HTTPException(status_code=404, detail="Resource was not found")
            except TypeError as error:
                raise HTTPException(status_code=405, detail=str(error))
            if not cleared:
                raise HTTPException(status_code=409, detail="Server is busy")
            return {"resource": resource_name, "state": "cleared"}

        @app.post("/jobs", status_code=202)
        def submit_job(payload: dict):
            job_type = str(payload.get("job_type", payload.get("command", "")))
            parameters = payload.get("parameters")
            if not job_type or not isinstance(parameters, dict):
                raise HTTPException(status_code=422, detail="Invalid job request")
            try:
                context = self.submit(job_type, parameters)
            except KeyError:
                raise HTTPException(status_code=422, detail="Unknown job type")
            except ValueError as error:
                raise HTTPException(status_code=409, detail=str(error))
            return context.snapshot()

        @app.get("/jobs/{job_id}")
        def job_status(job_id: str):
            context = self.jobs.get(job_id)
            if context is None:
                raise HTTPException(status_code=404, detail="Job was not found")
            return context.snapshot()

        @app.delete("/jobs/{job_id}", status_code=202)
        def cancel_job(job_id: str):
            context = self.cancel(job_id)
            if context is None:
                raise HTTPException(status_code=404, detail="Active job was not found")
            return context.snapshot()

        @app.post("/shutdown", status_code=202)
        def shutdown():
            self.shutdown_event.set()
            return {"state": "stopping"}

        return app

bind(storage_root)

Bind the Server to the Runtime-owned Storage Root.

源代码位于: src\blendjob\server.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
def bind(self, storage_root):
    """Bind the Server to the Runtime-owned Storage Root."""
    storage_root = Path(storage_root).resolve()
    if self.storage_root is not None:
        current = self.storage_root.resolve()
        if current != storage_root:
            raise RuntimeError(
                f"Job Server is already bound to another Storage Root: {current}"
            )
    self.storage_root = storage_root
    self.jobs_directory = storage_root / "jobs"
    for name, factory in tuple(self.resource_factories.items()):
        if name not in self.resources:
            self.resources[name] = factory(self)
    return self

add_resource(name, resource)

Register shared state owned for the full Server lifetime.

源代码位于: src\blendjob\server.py
157
158
159
160
161
162
163
164
165
def add_resource(self, name, resource):
    """Register shared state owned for the full Server lifetime."""
    if not name or "/" in name:
        raise ValueError(f"Invalid resource name: {name}")
    with self.lock:
        if name in self.resources:
            raise ValueError(f"Resource is already registered: {name}")
        self.resources[name] = resource
    return resource

resource(name)

Register a Resource factory initialized after Storage Root binding.

源代码位于: src\blendjob\server.py
167
168
169
170
171
172
173
174
175
176
177
178
179
def resource(self, name):
    """Register a Resource factory initialized after Storage Root binding."""
    def register(factory):
        if not name or "/" in name:
            raise ValueError(f"Invalid resource name: {name}")
        if name in self.resources or name in self.resource_factories:
            raise ValueError(f"Resource is already registered: {name}")
        self.resource_factories[name] = factory
        if self.storage_root is not None:
            self.resources[name] = factory(self)
        return factory

    return register

clear_resource(name)

Clear an idle Server Resource without racing a new Job submission.

源代码位于: src\blendjob\server.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
def clear_resource(self, name):
    """Clear an idle Server Resource without racing a new Job submission."""
    with self.lock:
        if self.active_job_id is not None or self._queued_job_count():
            return False
        try:
            resource = self.resources[name]
        except KeyError:
            raise KeyError(name) from None
        clear = getattr(resource, "clear", None)
        if clear is None:
            raise TypeError(f"Resource cannot be cleared: {name}")
        clear()
        return True

job(job_type)

Register handler(context, parameters) for a public job type.

源代码位于: src\blendjob\server.py
222
223
224
225
226
227
228
229
230
def job(self, job_type):
    """Register ``handler(context, parameters)`` for a public job type."""
    def register(handler):
        if job_type in self.handlers:
            raise ValueError(f"Job type is already registered: {job_type}")
        self.handlers[job_type] = handler
        return handler

    return register