|
| 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 |
0 commit comments