xtr_dependency_injection ¶
A bundle and kernel layer for the xtr libraries, built on wireup.
Each library ships one bundle; an application lists the bundles it wants in
its config/bundles.py — installing a package activates nothing — and the peers a
bundle requires arrive through @required_bundle. What comes out is a
plain wireup AsyncContainer: this package decides what goes into it, in
which order, for which environment, and runs the lifecycle around it.
UNIT_PARTICIPANT_TAG
module-attribute
¶
The tag a unit participant carries; an optional priority attribute, higher told first.
Injected
module-attribute
¶
Mark a parameter as container-provided, resolved by its type.
Alias of :data:Annotated[T, Autowire()] <Autowire> — the default
autowiring, resolved by the parameter's type annotation.
BUNDLE_PASS_PRIORITY
module-attribute
¶
Where a bundle overriding process runs: last in BEFORE_OPTIMIZATION.
The later stages still run after it.
DEFAULT_EXCLUDES
module-attribute
¶
DEFAULT_EXCLUDES: Final[tuple[str, ...]] = ('*.tests', '*.tests.*', '*.test_*', '*.conftest', '*.__main__')
fnmatch patterns of module names never imported by a scan.
Tests and entry points are not services, and importing __main__ would
run the application. Kernel(exclude=...) adds to these;
Kernel(default_excludes=False) drops them.
ServiceKey ¶
(provided type, qualifier) — the identity wireup registers a service under.
Decorates
dataclass
¶
What Definition.set_decorated_service records: a target key, priority and on-invalid.
Recorded by :meth:Definition.set_decorated_service.
Attributes:
-
key(ServiceKey) –The
(type, qualifier)of the decorated service. -
priority(int) –The decoration's priority. Higher wraps first.
-
on_invalid(OnInvalid) –Behavior when the target is not defined - :class:
~xtr_dependency_injection.decorator.as_decorator.OnInvalid.
Definition
dataclass
¶
Definition(key: ServiceKey, provider: object, kind: Literal['class', 'factory', 'instance'], lifetime: Lifetime, origin: Origin, priority: int | None = None, tags: dict[str, list[dict[str, object]]] = dict(), decorates: Decorates | None = None, before: tuple[type, ...] = (), after: tuple[type, ...] = (), arguments: dict[str, object] = dict(), lifetime_explicit: bool = False)
One service as the builder knows it, before it is compiled for wireup.
Attributes:
-
key(ServiceKey) –The type and qualifier it is provided under.
-
provider(object) –The class, factory function or instance that builds it.
-
kind(Literal['class', 'factory', 'instance']) –How
provideris registered:"class","factory"or"instance". -
lifetime(Lifetime) –How long wireup keeps what it builds.
-
origin(Origin) –Who contributed it.
-
priority(int | None) –Its position in ordered collections;
Nonemeans "no explicit priority", read as zero by :func:emission_orderand consumed by :func:sort_with_priorities. -
tags(dict[str, list[dict[str, object]]]) –Tag name → list of attribute mappings.
kernel.resetis the tag resettable services carry, read by the compiler. -
decorates(Decorates | None) –What service this definition decorates, when it does.
-
before(tuple[type, ...]) –Types this definition must precede in tagged collections (consumed by :func:
sort_with_priorities). -
after(tuple[type, ...]) –Types this definition must follow in tagged collections.
-
arguments(dict[str, object]) –Values for the provider's parameters, by name, given instead of injecting them. A value may hold an
env()placeholder or a%name%reference: it is resolved when the service is built. -
lifetime_explicit(bool) –Whether
lifetimewas asked for rather than left to its default — an autoconfiguration rule never overrides one that was.
set_argument ¶
Give the provider's parameter name the value value instead of injecting it.
This is how a bundle hands its config to a service: the value stays
on the definition, so an env() placeholder in it is resolved when
the service is built, and the report shows it.
set_arguments ¶
Replace every argument by arguments.
add_tag ¶
Add a tag name with the given attribute mapping.
Repeatable — each call appends one attribute mapping under name.
get_tag ¶
Return every attribute mapping added under name.
Returns an empty list when the tag was never added.
set_decorated_service ¶
set_decorated_service(target: type, /, *, qualifier: Hashable | None = None, priority: int = 0, on_invalid: OnInvalid = OnInvalid.EXCEPTION) -> Definition
Mark this definition as decorating (target, qualifier).
on_invalid chooses what happens when the target is not defined - see
:class:~xtr_dependency_injection.decorator.as_decorator.OnInvalid.
Origin
dataclass
¶
Who contributed a definition: the kernel, a bundle, or the application.
Attributes:
-
kind(Literal['kernel', 'bundle', 'app']) –"kernel","bundle"or"app". -
name(str) –The bundle's name, or
module:qualnameof the application object. -
note(str | None) –How it got there, when not directly — e.g.
"via autoconfigure of app.x:Y".
ContainerBuilder ¶
A whole-container view for a bundle or a compiler pass.
In phase build, only parameter reads/writes, container queries,
:meth:register_for_autoconfiguration and :meth:register_attribute_for_autoconfiguration
are allowed. In phase prepend, additionally
:meth:prepend_extension_config. In phase load and process,
definition/alias/tag mutations too. See the module docstring for the
full phase → allowed-operations table.
Bind this builder to state as origin.
has ¶
Return whether a definition or alias exists for (service, qualifier).
register ¶
register(service: type, /, *, qualifier: Hashable | None = None, lifetime: Lifetime | None = None) -> Definition
Register service as a class definition and return it, for further mutation.
lifetime is "singleton" when not given, and then left for
autoconfiguration to set. Allowed in phases load and process.
set_definition ¶
Overwrite the definition of definition.key with definition.
Allowed in phases load and process. Records the previous
origin as an override.
get_definition ¶
Return the definition of (service, qualifier).
Raises:
-
UnknownServiceError–If no such definition exists.
has_definition ¶
Return whether the definition of (service, qualifier) exists.
Unlike :meth:has, this does not follow aliases.
find_definition ¶
Return the definition (service, qualifier) resolves to, following aliases.
Raises:
-
UnknownServiceError–If neither a definition nor an alias resolves to a definition.
-
ServiceCircularReferenceError–If the aliases loop back on themselves.
remove_definition ¶
Remove the definition of (service, qualifier).
Raises:
-
UnknownServiceError–If no such definition exists.
get_definitions ¶
Return every definition, in declaration order.
set_alias ¶
set_alias(alias: type, target: type, /, *, alias_qualifier: Hashable | None = None, target_qualifier: Hashable | None = None) -> None
Register an alias from (alias, alias_qualifier) to (target, target_qualifier).
Allowed in phases load and process.
get_aliases ¶
Return every alias, alias_key -> target_key, in declaration order.
get_alias ¶
Return the target key for (alias, qualifier).
Raises:
-
UnknownServiceError–If no such alias exists.
has_alias ¶
Return whether (alias, qualifier) is aliased to another key.
remove_alias ¶
find_tagged_service_ids ¶
Return every definition tagged tag, mapped to its attribute list.
Definition order.
add_compiler_pass ¶
add_compiler_pass(compiler_pass: CompilerPassInterface, /, *, stage: PassStage = PassStage.BEFORE_OPTIMIZATION, priority: int = 0) -> None
Register compiler_pass to run in stage at priority.
Only allowed in phase build (from :meth:Bundle.build). The pass
runs with a builder bound to this builder's origin.
Raises:
-
TypeError–If
compiler_passdoes not implement :class:CompilerPassInterface.
log ¶
Record message in the compiler log, under compiler_pass.
register_for_autoconfiguration ¶
Return an :class:AutoconfigureRule for every subclass of type_.
Allowed in phases build and load.
ResolveInstanceofConditionalsPass applies each rule to every
non-kernel definition whose built
type has type_ in its __mro__ (a nominal subclass check). A
tag already carried on a definition wins over the rule's — explicit
stays.
register_attribute_for_autoconfiguration ¶
Register a callback called for every metadata item reader finds on a candidate.
AttributeAutoconfigurationPass runs the callback with the
registering bundle's :class:ServiceConfigurator.
set_parameter ¶
Set the parameter name to value.
Merges into the parameter sources under this builder's origin; a
leaf set twice by non-app sources with a different value raises
:class:ParameterConflictError at parameter-merge time.
Raises:
-
BuilderPhaseError–Once the
OPTIMIZEstage has resolved the parameters'%name%references — a parameter set later would keep its own unresolved. Set it from a pass that runsBEFORE_OPTIMIZATION.
get_extension_config ¶
Return the resolved config of a bundle, by name or by config type.
Raises:
-
MissingBundleError–If no active bundle has that name.
-
UnknownConfigTypeError–If no active bundle has that config type.
prepend_extension_config ¶
Adjust another bundle's config, before it is loaded.
Only allowed in phase prepend (from :meth:Bundle.prepend_extension).
Raises:
-
ConfigProviderError–If
bundleis a type owned by no known bundle, or if the target takes no config.
get_parameter ¶
Return the build-time parameter name (dotted path).
Allowed from phase build onward.
Raises:
-
ParameterNotFoundError–If the parameter is not set.
has_parameter ¶
Return whether the parameter name is defined.
Allowed from phase build onward.
get_parameter_bag ¶
Return the parameters of the build, merged, as stored.
%name% references are resolved by ResolveParameterPlaceHoldersPass.
ServiceConfigurator ¶
Defines services on behalf of one bundle.
set, instance, alias and load cover every way a bundle
contributes a service from load_extension.
Define services into state, as origin.
instance ¶
Provide obj itself, under its own type.
The key is always (type(obj), qualifier). Register an alias to
expose it under an interface (:meth:alias).
set ¶
set(target: type | Callable[..., object], /, *, qualifier: Hashable | None = None, lifetime: Lifetime | None = None) -> Definition
Register target — a class or a factory function — as a service.
lifetime is "singleton" when not given, and then left for
autoconfiguration to set.
A class is registered under its own type; a function under its evaluated return type. Same key + same provider is a no-op.
Raises:
-
InvalidArgumentTypeError–If
targetis not a class or a plain function, or is a function that does not annotate its return type.
alias ¶
alias(alias: type, target: type, /, *, alias_qualifier: Hashable | None = None, target_qualifier: Hashable | None = None) -> None
Register an alias from (alias, alias_qualifier) to (target, target_qualifier).
The alias target is validated at compile time (missing →
UnknownServiceError).
load ¶
Scan resources too, once every bundle has loaded, as this bundle's.
This is how a bundle scans a module only when a peer is active.
Bundle ¶
Base class of every bundle; declare one with @as_bundle.
A bundle is built with no arguments — discovery builds it that way — and
its hooks run in dependency order: build and prepend_extension
while the container is being wired, load_extension while services are
defined, process once every bundle loaded, boot and shutdown
around the container's life.
Attributes:
-
container(ContainerInterface | None) –The container the bundle has been booted against, set by the kernel right before :meth:
bootruns. It isNoneoutside a boot/shutdown cycle.
build ¶
Wire the container at compile time. Does nothing by default.
Runs once per build, in bundle order, before any bundle's
prepend_extension. Register compiler passes or autoconfiguration
rules here.
prepend_extension ¶
Adjust other bundles' configs before they are loaded. Does nothing by default.
Call builder.prepend_extension_config(target, transform) for every
adjustment.
load_extension ¶
Define this bundle's services from its resolved config. Does nothing by default.
process ¶
Inspect and adjust every definition, from every bundle. Does nothing by default.
boot
async
¶
Run once the container is built, before the application. Does nothing by default.
self.container is set by the kernel right before this runs.
Fail here, not on first use: bind handlers and check signatures now
when that is cheap.
shutdown
async
¶
Run as the kernel shuts down, before the container closes. Does nothing by default.
metadata
classmethod
¶
Return the metadata @as_bundle and @required_bundle recorded on this class.
@required_bundle declarations are merged in at call time so their
source order relative to @as_bundle does not matter.
Raises:
-
BundleDefinitionError–If the class was not decorated; a subclass of a decorated bundle is a different bundle and needs its own.
BundleMetadata
dataclass
¶
BundleMetadata(name: str, config: type[object], resources: tuple[str, ...] = (), required: tuple[RequiredBundle, ...] = tuple())
A bundle's declaration, as @as_bundle and @required_bundle recorded it.
Attributes:
-
name(str) –The name the bundle is known by everywhere.
-
config(type[object]) –Its config type;
NoConfigwhen it takes none. -
resources(tuple[str, ...]) –Modules and packages scanned like the application's.
-
required(tuple[RequiredBundle, ...]) –The peer bundles it depends on, in decoration order.
NoConfig
dataclass
¶
The config of a bundle that takes none. Never registered, never configurable.
RequiredBundle
dataclass
¶
CacheClearerInterface ¶
Bases: Protocol
Empties a cache that removing the cache directory does not reach.
A cache kept elsewhere — on a server, in a directory of its own —
survives the cache directory being removed. A service implementing this
interface is autoconfigured with the kernel.cache_clearer tag, and the
kernel's :class:~xtr_dependency_injection.cache_clearer.ChainCacheClearer
runs it.
ChainCacheClearer ¶
Bases: CacheClearerInterface
Runs several cache clearers in order, as a single one.
Run clearers, in the order given.
CacheWarmer ¶
Bases: CacheWarmerInterface, ABC
A cache warmer that knows how to write a file into the cache.
A subclass implements :meth:warm_up and :meth:is_optional, and writes
each file it produces through :meth:_write_cache_file.
CacheWarmerAggregate ¶
Bases: CacheWarmerInterface
Runs several cache warmers in order, as a single one.
Only the warmers that are not optional run, until
:meth:enable_optional_warmers lets the optional ones run too;
:meth:enable_only_optional_warmers runs nothing but those.
Run warmers, in the order given.
CacheWarmerInterface ¶
Bases: WarmableInterface, Protocol
Fills one part of the application's cache.
A service implementing this interface is autoconfigured with the
kernel.cache_warmer tag, and the kernel's
:class:~xtr_dependency_injection.cache_warmer.CacheWarmerAggregate runs it.
One that is not optional runs when the kernel boots with a cold cache;
every one runs on cache:warmup and cache:clear.
is_optional ¶
Tell whether this warmer may be skipped.
A warmer whose cache the application can also fill bit by bit, the first time each piece is needed, is optional: skipping it costs a slower first use, never a wrong answer. One whose cache the application cannot do without is not.
WarmableInterface ¶
Bases: Protocol
Fills its cache on demand, so the first use does not pay for it.
warm_up
async
¶
Fill the cache.
Parameters:
-
cache_dir(Path) –Where what is written at run time goes; the application may write there again later.
-
build_dir(Path | None, default:None) –Where what is only ever read goes, so a deploy can ship it on a read-only filesystem; often
cache_diritself.Nonewhen the caller gives no such place: write only tocache_dirthen.
WarmedCache ¶
Records, in the cache directory, which build its warmers last filled it for.
The kernel warms the cache when it boots only while the directory is not
fresh — it holds no stamp, or one written for another build — so every
later start skips the warm-up. cache:clear removes the directory, and
with it the stamp, so the next start warms again.
A build is told apart by its fingerprint: whatever, when it changes,
makes what the warmers wrote stale.
Keep the stamp in cache_dir, for the build fingerprint names.
is_fresh ¶
Tell whether the warmers already filled the cache directory for this build.
mark_fresh ¶
Record that the warmers filled the cache directory for this build.
The stamp is replaced in one step, so a process reading it meanwhile sees the old one or the new one.
lock
async
¶
Hold the cache directory, creating it, so one process at a time warms it.
The lock is a file lock: it holds across processes, and is let go whatever happens, even when the process dies. Where file locks are not available it holds nothing.
Waiting never blocks the event loop: the lock is tried without blocking, and between tries the task sleeps, so the wait can be cancelled.
CompilerPassInterface ¶
Bases: Protocol
A step of the compilation that sees, and may change, every definition.
A pass is registered with a stage and a priority — through
ContainerBuilder.add_compiler_pass from a bundle's build, or
@compiler_pass on a scanned class — and the compiler hands it a
:class:ContainerBuilder bound to whoever registered it, so what the pass
defines carries that origin. A bundle overriding process is itself a
pass.
AliasOf
dataclass
¶
Mark a config field as forwarding its value to another bundle's config.
Attributes:
-
bundle(str) –The name of the target bundle receiving the value.
Autowire
dataclass
¶
Bases: DependencyBase
Mark a parameter as container-provided — by type, by parameter, or from the environment.
Without :attr:param or :attr:env, the parameter is resolved by its
type, like :data:Injected. With :attr:param, the named dotted
parameter (such as kernel.name) is injected, any environment
placeholder in it resolved. With :attr:env, the environment variable
expression ("int:PORT", "json:file:SECRETS") is read when the
service is built, through the container's processors.
When the web framework is installed the marker is also one of its
dependency declarations, so the same annotation resolves through the
container inside a route; **fastapi exists for the framework's own
copy of a marker and is never written by hand.
Attributes:
-
param(str | None) –A dotted parameter name to inject.
-
env(str | None) –An environment variable expression to inject.
Raises:
-
ValueError–If both :attr:
paramand :attr:envare given.
Record what to inject; refuse naming both a parameter and a variable.
AutowireDecorated
dataclass
¶
Marks the parameter of a decorator that receives the decorated service.
Applied through Annotated[T, AutowireDecorated()] to the parameter
that receives the service the decorator wraps.
OnInvalid ¶
Bases: Enum
What a decorator does when the decorated service is not defined.
:attr:EXCEPTION fails the build, :attr:IGNORE drops the decorator,
and :attr:NULL keeps it under the target key with None for its
inner parameter.
EXCEPTION
class-attribute
instance-attribute
¶
Fail the build with :class:UnknownServiceError (the default).
IGNORE
class-attribute
instance-attribute
¶
Drop the decorator - it never enters the container.
NULL
class-attribute
instance-attribute
¶
Keep the decorator under the target key; feed None to its inner parameter.
Target
dataclass
¶
Bases: DependencyBase
Point a container-provided parameter at a specific qualifier.
Names the qualifier the container should resolve for this parameter, when several services of one type live under different qualifiers::
def __init__(self, mailer: Annotated[Mailer, Target("smtp")]) -> None: ...
On its own it marks the parameter as container-provided — no Autowire()
needed beside it, though Annotated[T, Autowire(), Target("smtp")] means the
same. It cannot sit beside Autowire(param=...) or Autowire(env=...): a
parameter is a parameter, an environment variable, or a qualified service.
When the web framework is installed the marker is also one of its
dependency declarations, so the same annotation resolves through the
container inside a route; **fastapi exists for the framework's own
copy of a marker and is never written by hand.
Attributes:
-
name(Hashable) –The qualifier of the service to inject.
Record the qualifier the container resolves for this parameter.
KernelReport
dataclass
¶
KernelReport(bundles: tuple[BundleReport, ...] = (), configs: tuple[ConfigReport, ...] = (), definitions: tuple[DefinitionReport, ...] = (), scan: ScanReport = ScanReport())
Everything one build decided, frozen when its container is compiled.
render ¶
Return the report as plain-text tables: one section, or all of them.
Fixed columns, no colours, nothing but the standard library — so the same text serves a terminal, a log line and an exception note.
FastapiIntegrationError ¶
Bases: DependencyInjectionError
The web integration cannot serve a request from the container.
Raised when a resolver runs with no attached kernel or no open request scope, and when a second kernel is attached to an application one already serves.
Attributes:
-
reason(str) –What the integration is missing.
Record what the integration is missing.
BootedKernel ¶
BootedKernel(container: AsyncContainer, kernel: KernelInterface, bundles: Sequence[AnyBundle], on_shutdown: Sequence[Callable[..., object]])
A booted kernel: its container, and the shutdown that releases it.
Use it as an async context manager, which shuts it down on exit::
async with await kernel.boot() as booted:
bus = await booted.container.get(MessageBusInterface)
Hold what shutdown needs: the booted bundles and the application's hooks.
shutdown
async
¶
Run the application's @on_shutdown hooks, then every bundle's, then close.
Once the hooks ran — they are what stops a worker or a scheduler the application started, and with it whatever keeps opening units — every unit of work still open, a request in flight, a message being handled, is waited for, up to thirty seconds: its scoped services use what the bundles and the container are about to close. Past that the kernel closes anyway, logging how many were left open. Once shut down, its container refuses to resolve.
Bundles shut down in reverse order, and the container is closed last —
running every generator factory's cleanup. No step stops the others:
once every one ran, the first BaseException (a cancellation, an
interrupt) propagates as it arrived; otherwise every Exception is
raised together. A second call does nothing.
Raises:
-
ExceptionGroup–If a step raised an
Exception, and none aBaseException.
CompiledKernel ¶
CompiledKernel(container: AsyncContainer, report: KernelReport, *, info: KernelInterface, bundles: Sequence[AnyBundle], on_boot: Sequence[Callable[..., object]], on_shutdown: Sequence[Callable[..., object]])
A compiled kernel: its container and report, ready to boot once.
The container exists already, so a framework integration can be wired
before the application starts; lifespan then boots and shuts down
around the application's life. Framework integrations that need the
engine container use engine_container(compiled) from
xtr_dependency_injection.integration.wireup.
Hold the container and everything boot and shutdown run.
boot
async
¶
Boot every bundle in order, then run the application's @on_boot hooks.
If a step raises, what already booted is shut down in reverse, the container is closed, and the error propagates — carrying a note when that rollback failed too, so the first failure stays the one raised.
Raises:
-
KernelAlreadyBootedError–If this compiled kernel booted before.
lifespan ¶
Return an ASGI-style lifespan: boot on enter, shut down on exit.
Kernel ¶
Kernel(package: str | ModuleType | None, /, *, env: str | None = None, debug: bool | None = None, name: str | None = None, bundles: Mapping[type[AnyBundle], Mapping[str, bool]] | None = None, resources: Sequence[str] | None = None, exclude: Sequence[str] = (), default_excludes: bool = True, allowed_envs: Sequence[str] | None = None, concurrent_scoped_access: bool = True, environ: Mapping[str, str] | None = None)
An application's kernel: which bundles, which resources, which environment.
Constructing one stores its arguments and nothing else; build,
boot and run do the work, each time afresh.
Store the kernel's recipe.
Parameters:
-
package(str | ModuleType | None) –The application package, scanned recursively: its dotted name or the module.
Kernel(__package__)in the package's ownkernel.pynames it once, where it cannot drift. -
env(str | None, default:None) –The environment; default
APP_ENV, else"dev". -
debug(bool | None, default:None) –Debug mode; default
APP_DEBUG, else true for"dev"and"test". -
name(str | None, default:None) –The application's name; default the package's last component.
-
bundles(Mapping[type[AnyBundle], Mapping[str, bool]] | None, default:None) –The bundle classes the application lists, mapped to their per-environment activity flags (
{"all": True}or{"dev": True}). WhenNonethe kernel imports<package>.config.bundles— or<package>.bundleswhen that is absent — and reads itsBUNDLESmapping. A class that list imports from a package that is not installed is stood in for, and reported disabled where its flags leave it inactive. -
resources(Sequence[str] | None, default:None) –What to scan instead of
package. -
exclude(Sequence[str], default:()) –fnmatchpatterns of modules never scanned, added toDEFAULT_EXCLUDES. A pattern starting with.is relative to the application package —".scripts"is"<package>.scripts"— whateverresourcesnames. -
default_excludes(bool, default:True) –Whether
DEFAULT_EXCLUDESapplies; false leavesexcludealone. -
allowed_envs(Sequence[str] | None, default:None) –The only environments the kernel accepts, and the only names a folder under
config/packages/orconfig/routes/may take. -
concurrent_scoped_access(bool, default:True) –Whether a scoped service is built under a lock, so tasks of one unit of work asking for it together get the one instance;
Falsedrops the lock, for a unit only ever used by one task at a time. -
environ(Mapping[str, str] | None, default:None) –Where
APP_ENV,APP_DEBUGand everyenv(...)placeholder are read;Nonereads the live process environment. A test gives each kernel its own.
Raises:
-
InvalidArgumentError–If
packageisNoneor empty — what__package__is in a script run on its own, outside any package.
debug
property
¶
Debug mode: the argument, else APP_DEBUG, else true for "dev" and "test".
Any other environment fails closed — debug is off — so a
security-relevant flag never defaults to on for a name the kernel does
not know. "prod" is off silently; an environment outside
"dev", "test" and "prod" warns once per process, saying
how to ask for debug explicitly.
Raises:
-
InvalidEnvironmentVariableError–If
APP_DEBUGis neither1/true/yes/onnor0/false/no/offor empty.
project_dir
property
¶
The nearest directory above the package with a pyproject.toml; else the package's.
with_env ¶
Return the same recipe for another environment.
An explicit debug carries over unless overridden.
build ¶
Run steps 1 to 6 and return the compiled container, not yet booted.
KernelInterface ¶
Bases: Protocol
The kernel, as a service: its identity, environment and what it decided.
package
property
¶
The application package, dotted; empty in a container built without a kernel.
project_dir
property
¶
The directory of the nearest pyproject.toml above the application.
bundles
property
¶
Active bundle names, in dependency order, "kernel" first.
report
property
¶
What the build decided; available once compiled, before boot.
ContainerBagInterface ¶
Bases: Protocol
The container's parameters, read-only, as an injectable service.
get ¶
Return the parameter name.
Raises:
-
ParameterNotFoundError–If no such parameter exists.
-
EnvPlaceholderError–If it holds an environment placeholder, which is resolved when injected, not read raw.
resolve_value ¶
Return value with every %name% reference in its strings resolved.
escape_value ¶
Return value with every % in its strings escaped as %%.
unescape_value ¶
Return value with every %% in its strings turned back into %.
ParameterBagInterface ¶
Bases: Protocol
The container's parameters, by dotted name (kernel.project_dir).
Parameters nest: setting app.mailer.host makes app a mapping, and
get("app") returns it whole.
add ¶
Merge parameters in, nested mappings merged and leaves replaced.
get ¶
Return the parameter name.
Raises:
-
ParameterNotFoundError–If no such parameter exists.
resolve_value ¶
Return value with every %name% reference in its strings resolved.
escape_value ¶
Return value with every % in its strings escaped as %%.
unescape_value ¶
Return value with every %% in its strings turned back into %.
EnvVarLoaderInterface ¶
Bases: Protocol
Loads variables from somewhere else — a secrets directory, a vault, a remote store.
A service implementing this interface is autoconfigured with the
container.env_var_loader tag. Loaders are asked, in registration
order, only for a variable the process environment does not set, and
each one is loaded once until the processor is reset.
load_env_vars ¶
Return every variable this loader provides, by name.
EnvVarProcessor ¶
EnvVarProcessor(environ: Mapping[str, str] | None = None, loaders: Iterable[EnvVarLoaderInterface] = (), get_parameter: Callable[[str], object] | None = None)
Bases: EnvVarProcessorInterface
The processor behind every built-in prefix, reading the process environment and loaders.
Resettable: :meth:reset forgets what the loaders provided, so the next
lookup asks them again — a worker picks up a rotated secret between
messages.
Read environ (the live process environment by default), then loaders.
Parameters:
-
environ(Mapping[str, str] | None, default:None) –Where variables are read first;
Nonereadsos.environat every lookup. -
loaders(Iterable[EnvVarLoaderInterface], default:()) –Asked, in order, for a variable
environlacks. -
get_parameter(Callable[[str], object] | None, default:None) –Resolves a parameter for
default:andresolve:; without one, those prefixes cannot name one.
EnvVarProcessorInterface ¶
Bases: Protocol
Processes the prefixes it provides, e.g. int in env("int:PORT").
A service implementing this interface is autoconfigured with the
container.env_var_processor tag and consulted for every prefix its
:meth:get_provided_types names; the kernel's own EnvVarProcessor
provides the built-in ones.
Reference
dataclass
¶
Points a config field at a service registered in the container.
Use it where a config would otherwise name something the bundle builds itself — a DSN, say — to have the bundle use a service the application already provides instead: a client with its own connection pool, credentials and lifecycle, which the application keeps closing.
A bundle checks it at boot with :meth:exists_in, so a reference to
nothing fails the application at startup, and fetches it with
:meth:resolve when the service needing it is built.
Attributes:
ScopeFactoryInterface ¶
Bases: Protocol
Opens a unit of work on the container it was built for.
The one method mirrors
:func:~xtr_dependency_injection.unit_of_work: it opens a scope — or
joins the one the container has open — and yields the scoped container,
which resolves scoped services as well as singletons.
unit_of_work ¶
Open a unit of work — or join the one already open — and yield its container.
Parameters:
-
join(bool, default:True) –Join the unit the container has open, if any.
Falseopens one of its own inside it, for work that is new rather than part of what is under way.
Raises:
-
InvalidArgumentTypeError–On entering, if the factory was built for a container no kernel built.
ServiceLocator ¶
Bases: ServiceCollectionInterface[T]
Builds services by name, from a container, only when asked.
Build one inside a factory that takes container: ContainerInterface::
def middleware_locator(container: ContainerInterface) -> ServiceLocator[Middleware]:
return ServiceLocator(container, {name: (Middleware, name) for name in NAMES})
Map each name in entries to the service key it stands for.
get
async
¶
Return the service named name, building it if needed.
Raises:
-
UnknownLocatorKeyError–If
namenames nothing here.
ServicesResetter ¶
Tracks built resettable singletons and resets them on demand.
Track nothing yet: services are tracked as the container builds them.
track ¶
Remember instance, to call its method on every :meth:reset.
Held weakly when it can be, so being resettable keeps nothing alive: when a weakly held instance is collected the entry is dropped immediately, so a long-running worker never accumulates dead references.
An instance that cannot be weak-referenced — one whose __slots__
omit __weakref__ — is instead held strongly, by a closure over it,
so it lives as long as the resetter does. Both cases key the entry by
id(instance) to skip a repeat of the same instance; that
deduplication is exact because a strongly held instance's id cannot
be reused while it is tracked, and a weakly held one's entry is gone
(dropped by the collection callback) before its id could be.
reset
async
¶
Call each tracked service's reset method, in tracking order; sync or async.
Every service is reset, whichever of them fail: one left holding the last unit of work's caches would bleed them into the next. Units of work still running are not waited for: each reset must be safe while they run.
Raises:
-
ExceptionGroup–Of what every failing reset raised, once all ran.
bundle_active ¶
Return whether the bundle name is active in the build builder sees.
Reads the kernel.bundles parameter the kernel registers before any
bundle hook runs. Usable from build onward, where that parameter
exists; before then it is absent and this returns False.
named_factory ¶
Name factory name and return it.
A bundle registering one factory per configured name — a store per lock
resource, a pool per cache pool — builds each as a closure of the same
function, so every one would be reported under that function's name. The
container's report, and every error naming the factory, reads far better
with lock_store_reports than with store. Only the names change:
the function, and how the engine calls it, stay as they are.
The function itself is renamed, not a copy of it: give it a function made for this name — a closure built per qualifier — never one shared by others.
sort_with_priorities ¶
sort_with_priorities(priorities: Mapping[str, int | None], constraints: Mapping[str, Mapping[str, Sequence[str]]], aliases: Mapping[str, Sequence[str]] | None = None) -> dict[str, int]
Sort items by priority first, then apply the constraints.
An explicit priority is a claim: constraints reorder such an item only
among the items sharing its priority, and a constraint that would need it
to cross a priority is an error. An item without priority is free: its
constraints place it, and it adopts the priority its place requires, 0
when that fits.
Parameters:
-
priorities(Mapping[str, int | None]) –Items in their default order, mapped to their declared priority,
Nonewhen none was declared. -
constraints(Mapping[str, Mapping[str, Sequence[str]]]) –See :func:
sort. -
aliases(Mapping[str, Sequence[str]] | None, default:None) –See :func:
sort.
Returns:
Raises:
-
ServiceOrderError–When the constraints are cyclic or contradict an explicit priority.
autoconfigure_tag ¶
Record a single tag rule on this class.
Repeatable: several @autoconfigure_tag(...) on one class accumulate.
is_container_supplied ¶
Return whether the container fills a parameter annotated annotation.
True for Injected[T], Annotated[T, Autowire(...)] and
Annotated[T, Target(...)] — also as a member of a union, such as
Injected[T] | None. Also true for a bare ServiceLocator[T], which the
container fills with a lazy name-keyed map of the services of T without a
marker, the way it fills a bare Sequence[T] or Mapping[Hashable, T]. A
library that calls a user's callable — a command, a message handler — asks
this to tell the parameters it passes itself from the ones the container
fills, so every such library agrees on what a marker is.
A type alias reads as what it stands for: type Mailer = Injected[Smtp]
is container-supplied, as Injected[Smtp] is.
on_boot ¶
Run the decorated function once the bundles have booted; highest priority first.
on_shutdown ¶
Run the decorated function first as the kernel shuts down; highest priority first.
when_not ¶
Leave the decorated object out of the given environments.
Repeating it widens the set. Combined with @when, both must pass.
qualified_name ¶
Return module:qualname for obj when both are strings, else repr.
This is how reports and errors name a provider — a function, class or the
like — as opposed to
:func:~xtr_dependency_injection.exception._naming.type_name, which names
a type in a service key.
current_unit_of_work ¶
Return the unit of work open in this context, or None outside one.
Raises:
-
UnitReadDuringSingletonBuildError–If a singleton is being built here, in a kernel built in debug mode: it would keep whichever unit happened to build it.
open_unit_of ¶
Return the unit of work open in this context on container's services, if any.
For a service that must work in the unit of whatever is being handled
when there is one, and from container itself otherwise. A unit of
another container — a second kernel's — is not container's.
Raises:
-
InvalidArgumentTypeError–If
containeris not one a kernel built.