跳转至

容器

按作用域解析共享实例。不替换类——issubclass / isinstance / 类型检查全部原样可用。

zoo_framework.core.container.container.ScopedContainer

Container resolving shared instances per scope.

Usage::

container = ScopedContainer()
container.register(ChannelManager, scope_kind=ScopeKind.PROCESS,
                   thread_safety=ThreadSafety.INSTANCE_GUARANTEED)
manager = container.resolve(ChannelManager, Scope.process())
源代码位于: zoo_framework/core/container/container.py
 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
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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
class ScopedContainer:
    """Container resolving shared instances per scope.

    Usage::

        container = ScopedContainer()
        container.register(ChannelManager, scope_kind=ScopeKind.PROCESS,
                           thread_safety=ThreadSafety.INSTANCE_GUARANTEED)
        manager = container.resolve(ChannelManager, Scope.process())
    """

    def __init__(self):
        """Construct an empty container."""
        # 保护注册表、实例表与细粒度锁表;可重入,允许工厂在同线程内递归解析
        self._lock = threading.RLock()
        self._registrations: dict[str, Registration] = {}
        self._instances: dict[tuple, Any] = {}
        self._creation_locks: dict[tuple, threading.Lock] = {}
        # "由容器保证串行"的项:按注册项划分的互斥锁;可重入,允许实例方法内再次进入
        self._exclusion_locks: dict[str, threading.RLock] = {}
        # "仅限单线程"的项:首次解析所在线程,作为该注册项的绑定线程
        self._thread_owners: dict[str, int] = {}
        # 测试接缝:按作用域注入的替代实现(见 replace / reset)
        self._overrides: dict[tuple, Callable[[], Any]] = {}

    # ------------------------------------------------------------------ 注册

    def register(
        self,
        target: type | str,
        *,
        scope_kind: str,
        thread_safety: str | None = None,
        name: str | None = None,
        factory: Callable[[], Any] | None = None,
        instance: Any = None,
        on_release: Callable[[Any], None] | None = None,
    ) -> str:
        """Register an item.

        Args:
            target: a class (identity derived from module + qualname) or a
                string (in which case ``name`` must be given)
            scope_kind: scope kind this item belongs to; see ``ScopeKind``
            thread_safety: thread-safety ownership declaration; see
                ``ThreadSafety``. **Required**: the default of None exists only
                so that "forgot to pass it" lands on the domain error below
                instead of a bare signature error; None itself is **not** a
                legal value and is rejected too
            name: explicit registration name, overriding the class-derived one
            factory: custom constructor; defaults to calling ``target`` itself
            instance: a pre-built instance; accepted for the process scope only
                (see below)
            on_release: destroy hook called when the instance is released,
                signature ``(instance) -> None``; fired **exactly once per
                instance** when its scope is released. No reference counting -
                across Workers "who holds, who releases" is ambiguous, and the
                matching entity of "one per session / per device" is scope
                ownership

        Returns:
            The registration id

        Raises:
            ValueError: invalid scope or thread-safety ownership, missing
                required declaration, duplicate registration, or an
                instance/scope combination that contradicts itself
            TypeError: ``target`` is neither a class nor a string
        """
        if scope_kind not in ScopeKind.ALL:
            raise ValueError(
                f"unknown scope kind {scope_kind!r}; expected one of {list(ScopeKind.ALL)}"
            )

        # 线程安全归属必填:隐式默认一个安全假设,正是 @cage 那类缺陷的温床
        if thread_safety is None:
            raise ValueError(
                f"registration {target!r} declares no thread-safety ownership;"
                f"expected one of {list(ThreadSafety.ALL)} (see: {ThreadSafety.DESCRIPTIONS})"
            )
        if thread_safety not in ThreadSafety.ALL:
            raise ValueError(
                f"unknown thread-safety ownership {thread_safety!r}; expected one of {list(ThreadSafety.ALL)}"
            )

        registered_type = self._resolve_registered_type(target, name)
        if name is not None:
            key = name
        else:
            # _resolve_registered_type 对字符串目标要求必须给出 name,故此处 registered_type
            # 必非 None。显式断言把这条不变量变成检查器可见的,也在原地写清了"为何可调用"。
            assert registered_type is not None
            key = qualified_name(registered_type)

        if factory is not None and instance is not None:
            raise ValueError(
                f"cannot register {key!r}: factory and instance are mutually exclusive"
            )

        # 显式声明:三条分支分别给 _Constant / 工厂 / 类,若交给 mypy 从首条分支推断,
        # 变量会被钉成 `_Constant`,后两条反而成了类型错误。
        product: Callable[[], Any]
        if instance is not None:
            # 预先构造的实例只可能是"一个"实例:会话级要的是每会话一个、原型级要的是
            # 每次一个,两者都与单实例相悖。静默共享会串会话,故明确拒绝。
            if scope_kind != ScopeKind.PROCESS:
                raise ValueError(
                    f"registration {key!r} passes a pre-built instance, which is only valid for the process scope;"
                    f"{scope_kind!r} requires per-scope construction"
                )
            product = _Constant(instance)
        elif factory is not None:
            product = factory
        elif registered_type is not None:
            product = registered_type
        else:
            raise ValueError(
                f"cannot register {key!r}: no construction source (neither a class, a factory nor an instance)"
            )

        registration = Registration(
            name=key,
            registered_type=registered_type,
            factory=product,
            scope_kind=scope_kind,
            thread_safety=thread_safety,
            explicit_name=name is not None,
            on_release=on_release,
        )

        with self._lock:
            existing = self._registrations.get(key)
            if existing is not None and not self._same_registration(existing, registration):
                raise ValueError(
                    f"registration {key!r} already exists ({existing!r}) and differs from this one; use replace() to override"
                )
            self._registrations[key] = registration
        return key

    def _resolve_registered_type(self, target: type | str, name: str | None) -> type | None:
        """Determine the registered type from the arguments; a string target requires an explicit name."""
        if isinstance(target, str):
            if not name:
                raise TypeError(f"registering the string {target!r} requires an explicit name")
            return None
        if not isinstance(target, type):
            raise TypeError(f"registration target must be a class or a string, got {target!r}")
        return target

    @staticmethod
    def _same_registration(existing: Registration, candidate: Registration) -> bool:
        """Whether two registrations are equivalent (keeps re-import idempotent, rather than silently rewriting).

        Construction sources are compared with ``==``: classes and functions by
        identity, pre-built instances by value identity via ``_Constant`` -
        two different ``_Constant`` wrappers around the same object are
        equivalent.
        """
        return (
            existing.registered_type is candidate.registered_type
            and existing.factory == candidate.factory
            and existing.scope_kind == candidate.scope_kind
            and existing.thread_safety == candidate.thread_safety
            and existing.on_release is candidate.on_release
        )

    # ------------------------------------------------------------------ 解析

    def resolve(self, target: type | str, scope: Scope) -> Any:
        """Resolve the instance within the given scope.

        The scope handle is **required**: there is no "process scope if
        omitted" default. A default handle is exactly what would silently break
        session isolation (see design D3).

        Args:
            target: the class given at registration, or its id (string)
            scope: scope handle

        Returns:
            The instance within this scope

        Raises:
            LookupError: the id is not registered
            ValueError: the scope handle does not match the registration's
                scope; or the thread-safety ownership does not permit this
                access (items declared container-serialized MUST be consumed
                via ``exclusive``; single-thread items MUST NOT be consumed
                from any thread other than the bound one)
        """
        self._check_scope_handle(scope)
        registration = self._require(target)
        self._check_scope_compatibility(registration, scope)
        # 注入了替代实现时跳过归属校验:假实现是测试自己的对象,其线程安全由测试负责,
        # 用真实实现的声明去拦它会挡住合法的注入(见 replace)
        if self._override_for(registration, scope) is None:
            self._guard_access(registration)
        return self._resolve_instance(registration, scope)

    @contextlib.contextmanager
    def exclusive(self, target: type | str, scope: Scope) -> Iterator[Any]:
        """Exclusive access: access to this item is serialized inside the ``with`` block.

        For items declared ``ThreadSafety.CONTAINER_SERIALIZED`` - they do not
        lock themselves; the container provides serialization. What is yielded
        is still the **real instance** (not a proxy), so type contracts are
        unaffected.

        The lock is per-registration and reentrant, so re-entering the same item
        inside an instance method does not deadlock.

        Args:
            target: the class given at registration, or its id
            scope: scope handle

        Yields:
            The instance within this scope
        """
        registration = self._require(target)
        with self._exclusion_lock(registration.name):
            yield self._resolve_instance(registration, scope)

    def _resolve_instance(self, registration: Registration, scope: Scope) -> Any:
        """Actual resolution: validate scope compatibility, then hit/build the cache.

        Callers must already have validated the scope handle type and the
        thread-safety ownership.
        """
        self._check_scope_compatibility(registration, scope)

        # 替代实现优先于一切缓存:注入即生效,且不进入本作用域的实例表(它不属于
        # 生命周期管理——没有 on_release 可言,换掉它也不必走 release)
        override = self._override_for(registration, scope)
        if override is not None:
            return override()

        # 原型级不缓存:每次解析都新建,作用域句柄在这里只是"允许解析"的凭据
        if registration.scope_kind == ScopeKind.PROTOTYPE:
            return registration.create()

        store_key = self._store_key(registration, scope)

        with self._lock:
            cached = self._instances.get(store_key, _MISSING)
        if cached is not _MISSING:
            return cached

        # 构造在细粒度锁下进行:不同注册项互不阻塞,同一项只构造一次
        with self._creation_lock(store_key):
            with self._lock:
                cached = self._instances.get(store_key, _MISSING)
            if cached is not _MISSING:
                return cached

            # 构造失败时不留下任何痕迹:实例只在成功之后才入缓存,故"半构造实例"不会
            # 被后续解析拿到,也不会在释放时被当成已建立实例处理
            instance = registration.create()

            with self._lock:
                self._instances[store_key] = instance
            return instance

    @staticmethod
    def _check_scope_handle(scope: Any) -> None:
        """Validate the scope handle's type."""
        if not isinstance(scope, Scope):
            raise TypeError(f"scope must be a Scope handle, got {scope!r}")

    def _guard_access(self, registration: Registration) -> None:
        """Admit or refuse this access according to the thread-safety ownership.

        The declaration is not decorative: if an item declared
        "container-serialized" could still be taken away via plain ``resolve``,
        the guarantee would be empty; the same holds for a "single-thread" item
        consumed from any thread.
        """
        if registration.thread_safety == ThreadSafety.CONTAINER_SERIALIZED:
            raise ValueError(
                f"registration {registration.name!r} is declared as"
                f"{ThreadSafety.CONTAINER_SERIALIZED!r} (container-serialized),"
                f"and must be consumed via exclusive(), not resolve()"
            )
        if registration.thread_safety == ThreadSafety.SINGLE_THREAD:
            self._claim_thread(registration)

    # ------------------------------------------------------------------ 释放

    def release(self, scope: Scope) -> list[str]:
        """Release every instance within the scope, firing each registration's destroy hook.

        Only instances **belonging to this handle** are released: releasing a
        session scope does not touch process-scoped items (they are process-wide
        by definition), and releasing a process-scoped handle does not touch
        session-scoped items.

        Idempotent: from the second call on the scope holds no instances, so no
        hooks fire and nothing raises. A hook that raises does not block the
        release of the remaining instances - otherwise one bad hook would leak
        all the others - the exception is logged.

        Args:
            scope: scope handle

        Returns:
            The ids of the instances released this call (cache order)
        """
        self._check_scope_handle(scope)
        subject = scope.cache_key
        if subject is None:
            # 原型级不缓存,没有可释放的实例
            return []
        return self._release_subject(subject)

    def _release_subject(self, subject: tuple) -> list[str]:
        """Release every instance held under a cache subject (process or one session).

        Injected overrides are not included: they are not in the instance table
        and need no lifecycle (see ``replace``).
        """
        with self._lock:
            victims = [
                (key, instance)
                for key, instance in self._instances.items()
                if key[: len(subject)] == subject
            ]
            # 先摘除再跑钩子:钩子里若再次解析同一项,拿到的是新实例而不是待销毁的那个
            for key, _ in victims:
                del self._instances[key]
            registrations = dict(self._registrations)

        released = []
        for key, instance in victims:
            name = key[-1]
            released.append(name)
            registration = registrations.get(name)
            self._run_release_hook(
                name, registration.on_release if registration is not None else None, instance
            )
        return released

    @staticmethod
    def _run_release_hook(name: str, hook, instance: Any) -> None:
        """Call the destroy hook; failures are logged only and do not interrupt the rest of the release."""
        if hook is None:
            return
        try:
            hook(instance)
        except Exception as e:
            LogUtils.error(
                f"releasing {name!r} raised during its destroy hook and was skipped: {e}",
                ScopedContainer.__name__,
            )

    def _claim_thread(self, registration: Registration) -> None:
        """Bind a "single-thread" registration to the thread that first consumed it.

        Later consumption from other threads MUST NOT silently return the
        instance. The spec allows "refuse or warn loudly"; this implementation
        chooses **refuse**: once the constraint is declared, out-of-bounds use
        should fail on the spot - if an item genuinely needs cross-thread
        sharing it belongs to "instance-guaranteed" or "container-serialized",
        so change the declaration rather than loosen the check.
        """
        current = threading.get_ident()
        with self._lock:
            owner = self._thread_owners.get(registration.name)
            if owner is None:
                self._thread_owners[registration.name] = current
                return
        if owner != current:
            raise ValueError(
                f"registration {registration.name!r} is declared as {ThreadSafety.SINGLE_THREAD!r}"
                f"(single-thread only), bound to thread {owner}; the current thread {current} may not consume it;"
                f"for cross-thread sharing, change the declaration to {ThreadSafety.INSTANCE_GUARANTEED!r} "
                f"or {ThreadSafety.CONTAINER_SERIALIZED!r}"
            )

    # ------------------------------------------------------------------ 内部工具

    def _require(self, target: type | str) -> Registration:
        """Fetch the registration; fail loudly listing known ids if not registered."""
        key = target if isinstance(target, str) else qualified_name(target)
        with self._lock:
            registration = self._registrations.get(key)
            if registration is None:
                known = sorted(self._registrations)
                raise LookupError(f"unknown id {key!r}; registered: {known}")
        return registration

    @staticmethod
    def _check_scope_compatibility(registration: Registration, scope: Scope) -> None:
        """Check that the scope handle is compatible with the registration's scope.

        Process-scoped items can be resolved with any handle (they are unique
        process-wide by definition); session-scoped items MUST be resolved with a
        session handle - resolving one with a process handle means "merging N
        sessions into one", and a prototype handle would mean "do not cache what
        must be cached" - both are silent semantic downgrades.
        """
        if registration.scope_kind != ScopeKind.SESSION:
            return
        if scope.kind != ScopeKind.SESSION:
            raise ValueError(
                f"registration {registration.name!r} is session-scoped and must be resolved with a session scope, got {scope!r}"
            )

    @staticmethod
    def _store_key(registration: Registration, scope: Scope) -> tuple:
        """The cache key for this registration under this handle.

        Process-scoped items always land on the process-level cache regardless
        of which handle was passed in - this is exactly how "a process-scoped
        registration is the same instance across sessions" is implemented.
        """
        if registration.scope_kind == ScopeKind.PROCESS:
            return ("process", registration.name)
        return ("session", scope.session_id, registration.name)

    def _creation_lock(self, store_key: tuple) -> threading.Lock:
        """Get the creation lock for this cache key (creates on demand)."""
        with self._lock:
            lock = self._creation_locks.get(store_key)
            if lock is None:
                lock = threading.Lock()
                self._creation_locks[store_key] = lock
            return lock

    def _exclusion_lock(self, name: str) -> threading.RLock:
        """Get the exclusive-access lock for this registration (creates on demand).

        Per registration, not per cache key: the scope instances under one
        declaration serialize independently of each other.
        """
        with self._lock:
            lock = self._exclusion_locks.get(name)
            if lock is None:
                lock = threading.RLock()
                self._exclusion_locks[name] = lock
            return lock

    # ------------------------------------------------------------------ 测试接缝

    def replace(
        self,
        target: type | str,
        scope: Scope,
        *,
        factory: Callable[[], Any] | None = None,
        instance: Any = None,
    ) -> None:
        """Inject an override for this scope (test seam).

        The replaced scope range is **the same** as the resolution scope range:
        override keys share the shape of cache keys, so a process-scoped item is
        replaced at **process** range (it is the one process-wide instance
        anyway) and a session-scoped item is replaced per session - exactly
        "the replacement applies only to the given scope".

        The injection takes effect immediately and drops instances already built
        for that scope. **Destroy hooks do NOT fire**: replacement is a test
        seam, not the end of a lifecycle; run ``release(scope)`` first if hooks
        are needed.

        Args:
            target: the class given at registration, or its id
            scope: scope handle
            factory: replacement constructor
            instance: replacement instance; mutually exclusive with factory

        Raises:
            ValueError: neither factory nor instance given, or both given
            LookupError: the id is not registered
        """
        self._check_scope_handle(scope)
        registration = self._require(target)
        self._check_scope_compatibility(registration, scope)

        if factory is not None and instance is not None:
            raise ValueError(
                f"replacing {registration.name!r}: factory and instance are mutually exclusive"
            )
        # 用 if/elif 而非三元表达式:后者让 mypy 只能看见 `Callable | None`,无法用上面
        # 那处检查把它收窄;显式分支才让它看到"此处必非 None"。
        product: Callable[[], Any]
        if instance is not None:
            product = _Constant(instance)
        elif factory is not None:
            product = factory
        else:
            raise ValueError(f"replacing {registration.name!r} requires a factory or an instance")
        with self._lock:
            self._overrides[self._override_key(registration, scope)] = product
            if registration.scope_kind != ScopeKind.PROTOTYPE:
                # 原型级本就不缓存,没有可丢的实例
                self._instances.pop(self._store_key(registration, scope), None)

    def reset(self) -> list[str]:
        """Reset the container: clear all overrides and release all built instances.

        "Back to initial state" means three things: no overrides, no leftover
        instances, no single-thread bindings. Registrations themselves are
        **kept** - they are the container's configuration, not test-produced
        state.

        Instances go through the same path as ``release``, so declared destroy
        hooks fire as usual and failures are logged only.

        Returns:
            The ids of the released instances (sorted, for easy assertion)
        """
        with self._lock:
            self._overrides.clear()
            self._thread_owners.clear()
            subjects = set()
            for key in self._instances:
                # 会话键形如 (session, sid, name),进程键形如 (process, name)
                subjects.add(key[:2] if key[0] == "session" else key[:1])

        released = []
        for subject in sorted(subjects):
            released.extend(self._release_subject(subject))
        return sorted(released)

    def _override_key(self, registration: Registration, scope: Scope) -> tuple:
        """The override key; same shape as ``_store_key``, so scope semantics match exactly."""
        if registration.scope_kind == ScopeKind.PROCESS:
            return ("process", registration.name)
        if registration.scope_kind == ScopeKind.PROTOTYPE:
            return ("prototype", registration.name)
        return ("session", scope.session_id, registration.name)

    def _override_for(self, registration: Registration, scope: Scope) -> Callable[[], Any] | None:
        """The override for this scope, or None when none was injected."""
        key = self._override_key(registration, scope)
        with self._lock:
            return self._overrides.get(key)

    # ------------------------------------------------------------------ 查询

    def registered(self) -> list[str]:
        """Currently registered ids (sorted)."""
        with self._lock:
            return sorted(self._registrations)

    def live_names(self, scope: Scope) -> list[str]:
        """The ids of instances currently held in this scope (sorted).

        One use is verifying that release actually took effect: it must be empty
        afterwards. Prototype-scoped items are not cached, so this is always
        empty for them.

        Args:
            scope: scope handle

        Returns:
            The registration ids of instances built under this handle
        """
        self._check_scope_handle(scope)
        subject = scope.cache_key
        if subject is None:
            return []
        with self._lock:
            return sorted(key[-1] for key in self._instances if key[: len(subject)] == subject)

    def get_registration(self, target: type | str) -> Registration:
        """Fetch the registration itself (for diagnostics and migration checks).

        Args:
            target: the class given at registration, or its id

        Returns:
            The corresponding ``Registration``
        """
        return self._require(target)

register

register(target: type | str, *, scope_kind: str, thread_safety: str | None = None, name: str | None = None, factory: Callable[[], Any] | None = None, instance: Any = None, on_release: Callable[[Any], None] | None = None) -> str

Register an item.

参数:

名称 类型 描述 默认
target type | str

a class (identity derived from module + qualname) or a string (in which case name must be given)

必需
scope_kind str

scope kind this item belongs to; see ScopeKind

必需
thread_safety str | None

thread-safety ownership declaration; see ThreadSafety. Required: the default of None exists only so that "forgot to pass it" lands on the domain error below instead of a bare signature error; None itself is not a legal value and is rejected too

None
name str | None

explicit registration name, overriding the class-derived one

None
factory Callable[[], Any] | None

custom constructor; defaults to calling target itself

None
instance Any

a pre-built instance; accepted for the process scope only (see below)

None
on_release Callable[[Any], None] | None

destroy hook called when the instance is released, signature (instance) -> None; fired exactly once per instance when its scope is released. No reference counting - across Workers "who holds, who releases" is ambiguous, and the matching entity of "one per session / per device" is scope ownership

None

返回:

类型 描述
str

The registration id

引发:

类型 描述
ValueError

invalid scope or thread-safety ownership, missing required declaration, duplicate registration, or an instance/scope combination that contradicts itself

TypeError

target is neither a class nor a string

源代码位于: zoo_framework/core/container/container.py
def register(
    self,
    target: type | str,
    *,
    scope_kind: str,
    thread_safety: str | None = None,
    name: str | None = None,
    factory: Callable[[], Any] | None = None,
    instance: Any = None,
    on_release: Callable[[Any], None] | None = None,
) -> str:
    """Register an item.

    Args:
        target: a class (identity derived from module + qualname) or a
            string (in which case ``name`` must be given)
        scope_kind: scope kind this item belongs to; see ``ScopeKind``
        thread_safety: thread-safety ownership declaration; see
            ``ThreadSafety``. **Required**: the default of None exists only
            so that "forgot to pass it" lands on the domain error below
            instead of a bare signature error; None itself is **not** a
            legal value and is rejected too
        name: explicit registration name, overriding the class-derived one
        factory: custom constructor; defaults to calling ``target`` itself
        instance: a pre-built instance; accepted for the process scope only
            (see below)
        on_release: destroy hook called when the instance is released,
            signature ``(instance) -> None``; fired **exactly once per
            instance** when its scope is released. No reference counting -
            across Workers "who holds, who releases" is ambiguous, and the
            matching entity of "one per session / per device" is scope
            ownership

    Returns:
        The registration id

    Raises:
        ValueError: invalid scope or thread-safety ownership, missing
            required declaration, duplicate registration, or an
            instance/scope combination that contradicts itself
        TypeError: ``target`` is neither a class nor a string
    """
    if scope_kind not in ScopeKind.ALL:
        raise ValueError(
            f"unknown scope kind {scope_kind!r}; expected one of {list(ScopeKind.ALL)}"
        )

    # 线程安全归属必填:隐式默认一个安全假设,正是 @cage 那类缺陷的温床
    if thread_safety is None:
        raise ValueError(
            f"registration {target!r} declares no thread-safety ownership;"
            f"expected one of {list(ThreadSafety.ALL)} (see: {ThreadSafety.DESCRIPTIONS})"
        )
    if thread_safety not in ThreadSafety.ALL:
        raise ValueError(
            f"unknown thread-safety ownership {thread_safety!r}; expected one of {list(ThreadSafety.ALL)}"
        )

    registered_type = self._resolve_registered_type(target, name)
    if name is not None:
        key = name
    else:
        # _resolve_registered_type 对字符串目标要求必须给出 name,故此处 registered_type
        # 必非 None。显式断言把这条不变量变成检查器可见的,也在原地写清了"为何可调用"。
        assert registered_type is not None
        key = qualified_name(registered_type)

    if factory is not None and instance is not None:
        raise ValueError(
            f"cannot register {key!r}: factory and instance are mutually exclusive"
        )

    # 显式声明:三条分支分别给 _Constant / 工厂 / 类,若交给 mypy 从首条分支推断,
    # 变量会被钉成 `_Constant`,后两条反而成了类型错误。
    product: Callable[[], Any]
    if instance is not None:
        # 预先构造的实例只可能是"一个"实例:会话级要的是每会话一个、原型级要的是
        # 每次一个,两者都与单实例相悖。静默共享会串会话,故明确拒绝。
        if scope_kind != ScopeKind.PROCESS:
            raise ValueError(
                f"registration {key!r} passes a pre-built instance, which is only valid for the process scope;"
                f"{scope_kind!r} requires per-scope construction"
            )
        product = _Constant(instance)
    elif factory is not None:
        product = factory
    elif registered_type is not None:
        product = registered_type
    else:
        raise ValueError(
            f"cannot register {key!r}: no construction source (neither a class, a factory nor an instance)"
        )

    registration = Registration(
        name=key,
        registered_type=registered_type,
        factory=product,
        scope_kind=scope_kind,
        thread_safety=thread_safety,
        explicit_name=name is not None,
        on_release=on_release,
    )

    with self._lock:
        existing = self._registrations.get(key)
        if existing is not None and not self._same_registration(existing, registration):
            raise ValueError(
                f"registration {key!r} already exists ({existing!r}) and differs from this one; use replace() to override"
            )
        self._registrations[key] = registration
    return key

resolve

resolve(target: type | str, scope: Scope) -> Any

Resolve the instance within the given scope.

The scope handle is required: there is no "process scope if omitted" default. A default handle is exactly what would silently break session isolation (see design D3).

参数:

名称 类型 描述 默认
target type | str

the class given at registration, or its id (string)

必需
scope Scope

scope handle

必需

返回:

类型 描述
Any

The instance within this scope

引发:

类型 描述
LookupError

the id is not registered

ValueError

the scope handle does not match the registration's scope; or the thread-safety ownership does not permit this access (items declared container-serialized MUST be consumed via exclusive; single-thread items MUST NOT be consumed from any thread other than the bound one)

源代码位于: zoo_framework/core/container/container.py
def resolve(self, target: type | str, scope: Scope) -> Any:
    """Resolve the instance within the given scope.

    The scope handle is **required**: there is no "process scope if
    omitted" default. A default handle is exactly what would silently break
    session isolation (see design D3).

    Args:
        target: the class given at registration, or its id (string)
        scope: scope handle

    Returns:
        The instance within this scope

    Raises:
        LookupError: the id is not registered
        ValueError: the scope handle does not match the registration's
            scope; or the thread-safety ownership does not permit this
            access (items declared container-serialized MUST be consumed
            via ``exclusive``; single-thread items MUST NOT be consumed
            from any thread other than the bound one)
    """
    self._check_scope_handle(scope)
    registration = self._require(target)
    self._check_scope_compatibility(registration, scope)
    # 注入了替代实现时跳过归属校验:假实现是测试自己的对象,其线程安全由测试负责,
    # 用真实实现的声明去拦它会挡住合法的注入(见 replace)
    if self._override_for(registration, scope) is None:
        self._guard_access(registration)
    return self._resolve_instance(registration, scope)

exclusive

exclusive(target: type | str, scope: Scope) -> Iterator[Any]

Exclusive access: access to this item is serialized inside the with block.

For items declared ThreadSafety.CONTAINER_SERIALIZED - they do not lock themselves; the container provides serialization. What is yielded is still the real instance (not a proxy), so type contracts are unaffected.

The lock is per-registration and reentrant, so re-entering the same item inside an instance method does not deadlock.

参数:

名称 类型 描述 默认
target type | str

the class given at registration, or its id

必需
scope Scope

scope handle

必需

产生:

类型 描述
Any

The instance within this scope

源代码位于: zoo_framework/core/container/container.py
@contextlib.contextmanager
def exclusive(self, target: type | str, scope: Scope) -> Iterator[Any]:
    """Exclusive access: access to this item is serialized inside the ``with`` block.

    For items declared ``ThreadSafety.CONTAINER_SERIALIZED`` - they do not
    lock themselves; the container provides serialization. What is yielded
    is still the **real instance** (not a proxy), so type contracts are
    unaffected.

    The lock is per-registration and reentrant, so re-entering the same item
    inside an instance method does not deadlock.

    Args:
        target: the class given at registration, or its id
        scope: scope handle

    Yields:
        The instance within this scope
    """
    registration = self._require(target)
    with self._exclusion_lock(registration.name):
        yield self._resolve_instance(registration, scope)

release

release(scope: Scope) -> list[str]

Release every instance within the scope, firing each registration's destroy hook.

Only instances belonging to this handle are released: releasing a session scope does not touch process-scoped items (they are process-wide by definition), and releasing a process-scoped handle does not touch session-scoped items.

Idempotent: from the second call on the scope holds no instances, so no hooks fire and nothing raises. A hook that raises does not block the release of the remaining instances - otherwise one bad hook would leak all the others - the exception is logged.

参数:

名称 类型 描述 默认
scope Scope

scope handle

必需

返回:

类型 描述
list[str]

The ids of the instances released this call (cache order)

源代码位于: zoo_framework/core/container/container.py
def release(self, scope: Scope) -> list[str]:
    """Release every instance within the scope, firing each registration's destroy hook.

    Only instances **belonging to this handle** are released: releasing a
    session scope does not touch process-scoped items (they are process-wide
    by definition), and releasing a process-scoped handle does not touch
    session-scoped items.

    Idempotent: from the second call on the scope holds no instances, so no
    hooks fire and nothing raises. A hook that raises does not block the
    release of the remaining instances - otherwise one bad hook would leak
    all the others - the exception is logged.

    Args:
        scope: scope handle

    Returns:
        The ids of the instances released this call (cache order)
    """
    self._check_scope_handle(scope)
    subject = scope.cache_key
    if subject is None:
        # 原型级不缓存,没有可释放的实例
        return []
    return self._release_subject(subject)

replace

replace(target: type | str, scope: Scope, *, factory: Callable[[], Any] | None = None, instance: Any = None) -> None

Inject an override for this scope (test seam).

The replaced scope range is the same as the resolution scope range: override keys share the shape of cache keys, so a process-scoped item is replaced at process range (it is the one process-wide instance anyway) and a session-scoped item is replaced per session - exactly "the replacement applies only to the given scope".

The injection takes effect immediately and drops instances already built for that scope. Destroy hooks do NOT fire: replacement is a test seam, not the end of a lifecycle; run release(scope) first if hooks are needed.

参数:

名称 类型 描述 默认
target type | str

the class given at registration, or its id

必需
scope Scope

scope handle

必需
factory Callable[[], Any] | None

replacement constructor

None
instance Any

replacement instance; mutually exclusive with factory

None

引发:

类型 描述
ValueError

neither factory nor instance given, or both given

LookupError

the id is not registered

源代码位于: zoo_framework/core/container/container.py
def replace(
    self,
    target: type | str,
    scope: Scope,
    *,
    factory: Callable[[], Any] | None = None,
    instance: Any = None,
) -> None:
    """Inject an override for this scope (test seam).

    The replaced scope range is **the same** as the resolution scope range:
    override keys share the shape of cache keys, so a process-scoped item is
    replaced at **process** range (it is the one process-wide instance
    anyway) and a session-scoped item is replaced per session - exactly
    "the replacement applies only to the given scope".

    The injection takes effect immediately and drops instances already built
    for that scope. **Destroy hooks do NOT fire**: replacement is a test
    seam, not the end of a lifecycle; run ``release(scope)`` first if hooks
    are needed.

    Args:
        target: the class given at registration, or its id
        scope: scope handle
        factory: replacement constructor
        instance: replacement instance; mutually exclusive with factory

    Raises:
        ValueError: neither factory nor instance given, or both given
        LookupError: the id is not registered
    """
    self._check_scope_handle(scope)
    registration = self._require(target)
    self._check_scope_compatibility(registration, scope)

    if factory is not None and instance is not None:
        raise ValueError(
            f"replacing {registration.name!r}: factory and instance are mutually exclusive"
        )
    # 用 if/elif 而非三元表达式:后者让 mypy 只能看见 `Callable | None`,无法用上面
    # 那处检查把它收窄;显式分支才让它看到"此处必非 None"。
    product: Callable[[], Any]
    if instance is not None:
        product = _Constant(instance)
    elif factory is not None:
        product = factory
    else:
        raise ValueError(f"replacing {registration.name!r} requires a factory or an instance")
    with self._lock:
        self._overrides[self._override_key(registration, scope)] = product
        if registration.scope_kind != ScopeKind.PROTOTYPE:
            # 原型级本就不缓存,没有可丢的实例
            self._instances.pop(self._store_key(registration, scope), None)

reset

reset() -> list[str]

Reset the container: clear all overrides and release all built instances.

"Back to initial state" means three things: no overrides, no leftover instances, no single-thread bindings. Registrations themselves are kept - they are the container's configuration, not test-produced state.

Instances go through the same path as release, so declared destroy hooks fire as usual and failures are logged only.

返回:

类型 描述
list[str]

The ids of the released instances (sorted, for easy assertion)

源代码位于: zoo_framework/core/container/container.py
def reset(self) -> list[str]:
    """Reset the container: clear all overrides and release all built instances.

    "Back to initial state" means three things: no overrides, no leftover
    instances, no single-thread bindings. Registrations themselves are
    **kept** - they are the container's configuration, not test-produced
    state.

    Instances go through the same path as ``release``, so declared destroy
    hooks fire as usual and failures are logged only.

    Returns:
        The ids of the released instances (sorted, for easy assertion)
    """
    with self._lock:
        self._overrides.clear()
        self._thread_owners.clear()
        subjects = set()
        for key in self._instances:
            # 会话键形如 (session, sid, name),进程键形如 (process, name)
            subjects.add(key[:2] if key[0] == "session" else key[:1])

    released = []
    for subject in sorted(subjects):
        released.extend(self._release_subject(subject))
    return sorted(released)

registered

registered() -> list[str]

Currently registered ids (sorted).

源代码位于: zoo_framework/core/container/container.py
def registered(self) -> list[str]:
    """Currently registered ids (sorted)."""
    with self._lock:
        return sorted(self._registrations)

live_names

live_names(scope: Scope) -> list[str]

The ids of instances currently held in this scope (sorted).

One use is verifying that release actually took effect: it must be empty afterwards. Prototype-scoped items are not cached, so this is always empty for them.

参数:

名称 类型 描述 默认
scope Scope

scope handle

必需

返回:

类型 描述
list[str]

The registration ids of instances built under this handle

源代码位于: zoo_framework/core/container/container.py
def live_names(self, scope: Scope) -> list[str]:
    """The ids of instances currently held in this scope (sorted).

    One use is verifying that release actually took effect: it must be empty
    afterwards. Prototype-scoped items are not cached, so this is always
    empty for them.

    Args:
        scope: scope handle

    Returns:
        The registration ids of instances built under this handle
    """
    self._check_scope_handle(scope)
    subject = scope.cache_key
    if subject is None:
        return []
    with self._lock:
        return sorted(key[-1] for key in self._instances if key[: len(subject)] == subject)

get_registration

get_registration(target: type | str) -> Registration

Fetch the registration itself (for diagnostics and migration checks).

参数:

名称 类型 描述 默认
target type | str

the class given at registration, or its id

必需

返回:

类型 描述
Registration

The corresponding Registration

源代码位于: zoo_framework/core/container/container.py
def get_registration(self, target: type | str) -> Registration:
    """Fetch the registration itself (for diagnostics and migration checks).

    Args:
        target: the class given at registration, or its id

    Returns:
        The corresponding ``Registration``
    """
    return self._require(target)

作用域

zoo_framework.core.container.scope.Scope

Scope handle.

The handle is an immutable identity, safe to pass across threads; it does not carry the instance cache - the cache belongs to the container.

属性:

名称 类型 描述
kind

the scope kind, see ScopeKind for values

session_id

the session identity; carried only by a session scope, None otherwise

源代码位于: zoo_framework/core/container/scope.py
class Scope:
    """Scope handle.

    The handle is an immutable identity, safe to pass across threads; it
    does **not** carry the instance cache - the cache belongs to the
    container.

    Attributes:
        kind: the scope kind, see ``ScopeKind`` for values
        session_id: the session identity; carried only by a session scope,
            None otherwise
    """

    __slots__ = ("kind", "session_id")

    def __init__(self, kind: str, session_id: str | None = None):
        """Construct a scope handle.

        Args:
            kind: the scope kind
            session_id: the session identity; only a session scope needs it

        Raises:
            ValueError: the kind is unrecognized, or the session identity
                does not match the kind (missing or extra)
        """
        if kind not in ScopeKind.ALL:
            raise ValueError(f"unknown scope kind {kind!r}; expected one of {list(ScopeKind.ALL)}")

        # Without a session id, a session scope cannot tell sessions apart and
        # the cache would degenerate to process level - a silent semantic
        # downgrade, so reject it here rather than fill in a default identity
        if kind == ScopeKind.SESSION and not session_id:
            raise ValueError("a session scope requires a session id")

        # A non-session scope carrying a session id means the caller believed
        # it was isolating when it was not; reject that explicitly too
        if kind != ScopeKind.SESSION and session_id is not None:
            raise ValueError(f"a {kind} scope does not accept a session id, got {session_id!r}")

        self.kind = kind
        self.session_id = session_id

    @classmethod
    def process(cls) -> "Scope":
        """The process-level scope handle."""
        return cls(ScopeKind.PROCESS)

    @classmethod
    def session(cls, session_id: str) -> "Scope":
        """The session-level scope handle.

        Args:
            session_id: the session identity, usually taken from
                ``RunIdentity.session_id``
        """
        return cls(ScopeKind.SESSION, session_id)

    @classmethod
    def prototype(cls) -> "Scope":
        """The prototype-level scope handle (a fresh build per resolution)."""
        return cls(ScopeKind.PROTOTYPE)

    @classmethod
    def of(cls, identity: Any) -> "Scope":
        """Derive a session scope from a run identity.

        This is an **explicit** call: the handle is still passed into the
        container by the caller; it only saves the manual extraction of
        ``session_id``. When the identity is None it is rejected explicitly,
        not falling back to the process level - that would silently merge two
        sessions into one.

        Args:
            identity: a ``RunIdentity`` instance

        Raises:
            ValueError: the identity is None or carries no session identity
        """
        if identity is None:
            raise ValueError(
                "no run identity: cannot derive a session scope (MUST NOT silently fall back to the process scope)"
            )
        session_id = getattr(identity, "session_id", None)
        if not session_id:
            raise ValueError(
                f"run identity {identity!r} carries no session id: cannot derive a session scope"
            )
        return cls.session(session_id)

    @property
    def cache_key(self) -> tuple | None:
        """The cache subject of the scope; a prototype scope does not cache and returns None."""
        if self.kind == ScopeKind.PROTOTYPE:
            return None
        if self.kind == ScopeKind.PROCESS:
            return PROCESS_SCOPE_KEY
        return ("session", self.session_id)

    def __eq__(self, other: Any) -> bool:
        if not isinstance(other, Scope):
            return NotImplemented
        return (self.kind, self.session_id) == (other.kind, other.session_id)

    def __hash__(self) -> int:
        return hash((self.kind, self.session_id))

    def __repr__(self) -> str:
        if self.kind == ScopeKind.SESSION:
            return f"Scope(session={self.session_id!r})"
        return f"Scope({self.kind})"

cache_key property

cache_key: tuple | None

The cache subject of the scope; a prototype scope does not cache and returns None.

process classmethod

process() -> Scope

The process-level scope handle.

源代码位于: zoo_framework/core/container/scope.py
@classmethod
def process(cls) -> "Scope":
    """The process-level scope handle."""
    return cls(ScopeKind.PROCESS)

session classmethod

session(session_id: str) -> Scope

The session-level scope handle.

参数:

名称 类型 描述 默认
session_id str

the session identity, usually taken from RunIdentity.session_id

必需
源代码位于: zoo_framework/core/container/scope.py
@classmethod
def session(cls, session_id: str) -> "Scope":
    """The session-level scope handle.

    Args:
        session_id: the session identity, usually taken from
            ``RunIdentity.session_id``
    """
    return cls(ScopeKind.SESSION, session_id)

prototype classmethod

prototype() -> Scope

The prototype-level scope handle (a fresh build per resolution).

源代码位于: zoo_framework/core/container/scope.py
@classmethod
def prototype(cls) -> "Scope":
    """The prototype-level scope handle (a fresh build per resolution)."""
    return cls(ScopeKind.PROTOTYPE)

of classmethod

of(identity: Any) -> Scope

Derive a session scope from a run identity.

This is an explicit call: the handle is still passed into the container by the caller; it only saves the manual extraction of session_id. When the identity is None it is rejected explicitly, not falling back to the process level - that would silently merge two sessions into one.

参数:

名称 类型 描述 默认
identity Any

a RunIdentity instance

必需

引发:

类型 描述
ValueError

the identity is None or carries no session identity

源代码位于: zoo_framework/core/container/scope.py
@classmethod
def of(cls, identity: Any) -> "Scope":
    """Derive a session scope from a run identity.

    This is an **explicit** call: the handle is still passed into the
    container by the caller; it only saves the manual extraction of
    ``session_id``. When the identity is None it is rejected explicitly,
    not falling back to the process level - that would silently merge two
    sessions into one.

    Args:
        identity: a ``RunIdentity`` instance

    Raises:
        ValueError: the identity is None or carries no session identity
    """
    if identity is None:
        raise ValueError(
            "no run identity: cannot derive a session scope (MUST NOT silently fall back to the process scope)"
        )
    session_id = getattr(identity, "session_id", None)
    if not session_id:
        raise ValueError(
            f"run identity {identity!r} carries no session id: cannot derive a session scope"
        )
    return cls.session(session_id)

zoo_framework.core.container.scope.ScopeKind

Scope kinds.

源代码位于: zoo_framework/core/container/scope.py
class ScopeKind:
    """Scope kinds."""

    PROCESS = "process"
    SESSION = "session"
    PROTOTYPE = "prototype"

    ALL = (PROCESS, SESSION, PROTOTYPE)

注册

zoo_framework.core.container.registration

A registration.

A registration records "how to build an instance of a type, which scope it belongs to, and its thread-safety ownership". The id is taken as module + qualified name rather than the bare class name (see design D2): the bare name would let two same-named classes defined in different places overwrite each other, silently, when resolving to the wrong object.

The type contract is guarded by this object: registered_type is always the class provided at registration; the container neither replaces it nor returns a proxy, so isinstance / issubclass keep working as usual.

Registration

A registration.

属性:

名称 类型 描述
name

the registration id (unique within the process)

registered_type

the type given at registration; carries the type contract, may be None (when registered by name)

scope_kind

which scope kind it belongs to

thread_safety

the thread-safety ownership declaration

explicit_name

whether the id was given explicitly (rather than derived from the class)

on_release

the release hook called when the instance is released; signature (instance) -> None

源代码位于: zoo_framework/core/container/registration.py
class Registration:
    """A registration.

    Attributes:
        name: the registration id (unique within the process)
        registered_type: the type given at registration; carries the type
            contract, may be None (when registered by name)
        scope_kind: which scope kind it belongs to
        thread_safety: the thread-safety ownership declaration
        explicit_name: whether the id was given explicitly (rather than
            derived from the class)
        on_release: the release hook called when the instance is released;
            signature ``(instance) -> None``
    """

    __slots__ = (
        "explicit_name",
        "factory",
        "name",
        "on_release",
        "registered_type",
        "scope_kind",
        "thread_safety",
    )

    def __init__(
        self,
        name: str,
        registered_type: type | None,
        factory: Callable[[], Any],
        scope_kind: str,
        thread_safety: str,
        explicit_name: bool = False,
        on_release: Callable[[Any], None] | None = None,
    ):
        self.name = name
        self.registered_type = registered_type
        self.factory = factory
        self.scope_kind = scope_kind
        self.thread_safety = thread_safety
        self.explicit_name = explicit_name
        self.on_release = on_release

    def create(self) -> Any:
        """Build one instance in the way given at registration."""
        return self.factory()

    def __repr__(self) -> str:
        return (
            f"Registration(name={self.name!r}, scope={self.scope_kind!r}, "
            f"thread_safety={self.thread_safety!r})"
        )

create

create() -> Any

Build one instance in the way given at registration.

源代码位于: zoo_framework/core/container/registration.py
def create(self) -> Any:
    """Build one instance in the way given at registration."""
    return self.factory()

qualified_name

qualified_name(cls: type) -> str

Get the process-unique identity of a type (module + qualified name).

参数:

名称 类型 描述 默认
cls type

the class to identify

必需

返回:

类型 描述
str

An identity like pkg.mod.Outer.Inner

引发:

类型 描述
TypeError

the argument is not a class

源代码位于: zoo_framework/core/container/registration.py
def qualified_name(cls: type) -> str:
    """Get the process-unique identity of a type (module + qualified name).

    Args:
        cls: the class to identify

    Returns:
        An identity like ``pkg.mod.Outer.Inner``

    Raises:
        TypeError: the argument is not a class
    """
    if not isinstance(cls, type):
        raise TypeError(f"registration id can only be derived from a class, got {cls!r}")
    return f"{cls.__module__}.{cls.__qualname__}"