Skip to content

Commit d0bd44f

Browse files
committed
feat: integrate module-level layers
1 parent d953a3e commit d0bd44f

11 files changed

Lines changed: 1222 additions & 10 deletions

File tree

‎src/celerity/bootstrap/__init__.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
"""Application bootstrap and module graph."""
2+
3+
from celerity.bootstrap.module_graph import (
4+
build_module_graph,
5+
register_module_graph,
6+
walk_module_graph,
7+
)
8+
9+
__all__ = [
10+
"build_module_graph",
11+
"register_module_graph",
12+
"walk_module_graph",
13+
]
Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
"""Module graph builder and DI registrar."""
2+
3+
from __future__ import annotations
4+
5+
import logging
6+
from dataclasses import dataclass, field
7+
from typing import TYPE_CHECKING, Any
8+
9+
from celerity.metadata.keys import MODULE, get_metadata
10+
11+
if TYPE_CHECKING:
12+
from celerity.di.container import Container
13+
from celerity.types.container import Provider
14+
from celerity.types.module import (
15+
FunctionHandlerDefinition,
16+
GuardDefinition,
17+
ModuleMetadata,
18+
)
19+
20+
logger = logging.getLogger("celerity.bootstrap")
21+
22+
23+
@dataclass
24+
class ModuleNode:
25+
"""A single node in the module dependency graph."""
26+
27+
module_class: type
28+
own_tokens: set[Any] = field(default_factory=set)
29+
exports: set[Any] = field(default_factory=set)
30+
imports: list[type] = field(default_factory=list)
31+
controllers: list[type] = field(default_factory=list)
32+
function_handlers: list[FunctionHandlerDefinition] = field(default_factory=list)
33+
guards: list[type | GuardDefinition] = field(default_factory=list)
34+
providers: list[type | Provider] = field(default_factory=list)
35+
layers: list[Any] = field(default_factory=list)
36+
37+
38+
type ModuleGraph = dict[type, ModuleNode]
39+
40+
41+
def build_module_graph(root_module: type) -> ModuleGraph:
42+
"""Walk the module tree depth-first, collecting metadata.
43+
44+
Args:
45+
root_module: The root ``@module``-decorated class.
46+
47+
Returns:
48+
A dict mapping each module class to its ``ModuleNode``.
49+
50+
Raises:
51+
RuntimeError: If a circular module import is detected.
52+
53+
Example::
54+
55+
@module(controllers=[OrderController], providers=[OrderService])
56+
class AppModule:
57+
pass
58+
59+
graph = build_module_graph(AppModule)
60+
"""
61+
graph: ModuleGraph = {}
62+
resolving: set[type] = set()
63+
64+
def walk(module_class: type, import_chain: list[type]) -> None:
65+
if module_class in graph:
66+
return
67+
68+
if module_class in resolving:
69+
cycle = " -> ".join(m.__name__ for m in [*import_chain, module_class])
70+
raise RuntimeError(f"Circular module import detected: {cycle}")
71+
72+
resolving.add(module_class)
73+
metadata: ModuleMetadata | None = get_metadata(module_class, MODULE)
74+
75+
if metadata is None:
76+
resolving.discard(module_class)
77+
graph[module_class] = ModuleNode(module_class=module_class)
78+
return
79+
80+
for imported in metadata.imports or []:
81+
walk(imported, [*import_chain, module_class])
82+
83+
own_tokens: set[Any] = set()
84+
for provider in metadata.providers or []:
85+
if isinstance(provider, type):
86+
own_tokens.add(provider)
87+
else:
88+
own_tokens.add(provider)
89+
90+
for ctrl in metadata.controllers or []:
91+
own_tokens.add(ctrl)
92+
93+
for g in metadata.guards or []:
94+
if isinstance(g, type):
95+
own_tokens.add(g)
96+
97+
resolving.discard(module_class)
98+
graph[module_class] = ModuleNode(
99+
module_class=module_class,
100+
own_tokens=own_tokens,
101+
exports=set(metadata.exports or []),
102+
imports=metadata.imports or [],
103+
controllers=metadata.controllers or [],
104+
function_handlers=metadata.function_handlers or [],
105+
guards=metadata.guards or [],
106+
providers=metadata.providers or [],
107+
layers=metadata.layers or [],
108+
)
109+
110+
walk(root_module, [])
111+
return graph
112+
113+
114+
def register_module_graph(graph: ModuleGraph, container: Container) -> None:
115+
"""Register all providers from the module graph into a DI container.
116+
117+
Args:
118+
graph: The module graph built by ``build_module_graph``.
119+
container: The DI container to register providers in.
120+
"""
121+
122+
for node in graph.values():
123+
for provider in node.providers:
124+
if isinstance(provider, type):
125+
container.register_class(provider)
126+
else:
127+
container.register(provider, provider)
128+
129+
for ctrl in node.controllers:
130+
if not container.has(ctrl):
131+
container.register_class(ctrl)
132+
133+
for g in node.guards:
134+
if isinstance(g, type) and not container.has(g):
135+
container.register_class(g)
136+
137+
138+
def walk_module_graph(root_module: type, container: Container) -> ModuleGraph:
139+
"""Build the module graph and register all providers in one call.
140+
141+
Args:
142+
root_module: The root ``@module``-decorated class.
143+
container: The DI container to register providers in.
144+
145+
Returns:
146+
The built module graph.
147+
"""
148+
graph = build_module_graph(root_module)
149+
register_module_graph(graph, container)
150+
return graph

‎src/celerity/decorators/module.py‎

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
from __future__ import annotations
44

5-
from typing import TYPE_CHECKING
5+
from typing import TYPE_CHECKING, Any
66

77
from celerity.metadata.keys import MODULE, set_metadata
88
from celerity.types.module import ModuleMetadata
@@ -23,6 +23,7 @@ def module(
2323
providers: list[type | Provider] | None = None,
2424
imports: list[type] | None = None,
2525
exports: list[InjectionToken] | None = None,
26+
layers: list[Any] | None = None,
2627
) -> Callable[[type], type]:
2728
"""Declare a module -- the organisational unit for grouping
2829
controllers, providers, and sub-modules.
@@ -38,6 +39,8 @@ def module(
3839
providers: Provider classes or provider dicts.
3940
imports: Other modules to import.
4041
exports: Tokens to export for importing modules.
42+
layers: Application-level layers applied to all handlers
43+
in this module.
4144
4245
Returns:
4346
A class decorator that attaches module metadata.
@@ -49,18 +52,10 @@ def module(
4952
providers=[OrderService, PaymentService],
5053
imports=[DatabaseModule],
5154
exports=[OrderService],
55+
layers=[LoggingLayer, MetricsLayer],
5256
)
5357
class OrderModule:
5458
pass
55-
56-
@module(
57-
function_handlers=[
58-
{"handler": process_event, "trigger": "consumer"},
59-
],
60-
guards=[JwtGuard],
61-
)
62-
class EventModule:
63-
pass
6459
"""
6560

6661
def decorator(cls: type) -> type:
@@ -71,6 +66,7 @@ def decorator(cls: type) -> type:
7166
providers=providers,
7267
imports=imports,
7368
exports=exports,
69+
layers=layers,
7470
)
7571
set_metadata(cls, MODULE, metadata)
7672
return cls

‎src/celerity/di/__init__.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
"""Dependency injection container and utilities."""
2+
3+
from celerity.di.container import Container
4+
from celerity.di.dependency_tokens import get_class_dependency_tokens
5+
from celerity.di.tokens import APP_CONFIG, RUNTIME_APP
6+
7+
__all__ = [
8+
"APP_CONFIG",
9+
"RUNTIME_APP",
10+
"Container",
11+
"get_class_dependency_tokens",
12+
]

0 commit comments

Comments
 (0)