engin 0.0.8__tar.gz → 0.0.9__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. {engin-0.0.8 → engin-0.0.9}/CHANGELOG.md +16 -0
  2. {engin-0.0.8 → engin-0.0.9}/PKG-INFO +1 -1
  3. {engin-0.0.8 → engin-0.0.9}/examples/asgi/main.py +3 -1
  4. engin-0.0.9/examples/fastapi/app.py +29 -0
  5. {engin-0.0.8 → engin-0.0.9}/examples/fastapi/routes/cats/block.py +4 -6
  6. {engin-0.0.8 → engin-0.0.9}/pyproject.toml +1 -1
  7. {engin-0.0.8 → engin-0.0.9}/src/engin/_block.py +2 -0
  8. {engin-0.0.8 → engin-0.0.9}/src/engin/_dependency.py +19 -1
  9. engin-0.0.9/src/engin/_graph.py +50 -0
  10. {engin-0.0.8 → engin-0.0.9}/src/engin/ext/asgi.py +6 -1
  11. engin-0.0.9/src/engin/ext/fastapi.py +168 -0
  12. {engin-0.0.8 → engin-0.0.9}/src/engin/scripts/graph.py +68 -16
  13. engin-0.0.8/examples/fastapi/app.py +0 -25
  14. engin-0.0.8/src/engin/_graph.py +0 -39
  15. engin-0.0.8/src/engin/ext/fastapi.py +0 -38
  16. {engin-0.0.8 → engin-0.0.9}/.github/workflows/check.yaml +0 -0
  17. {engin-0.0.8 → engin-0.0.9}/.github/workflows/publish.yaml +0 -0
  18. {engin-0.0.8 → engin-0.0.9}/.gitignore +0 -0
  19. {engin-0.0.8 → engin-0.0.9}/.readthedocs.yaml +0 -0
  20. {engin-0.0.8 → engin-0.0.9}/LICENSE +0 -0
  21. {engin-0.0.8 → engin-0.0.9}/README.md +0 -0
  22. {engin-0.0.8 → engin-0.0.9}/docs/concepts/engin.md +0 -0
  23. {engin-0.0.8 → engin-0.0.9}/docs/concepts/invocations.md +0 -0
  24. {engin-0.0.8 → engin-0.0.9}/docs/concepts/lifecycle.md +0 -0
  25. {engin-0.0.8 → engin-0.0.9}/docs/concepts/providers.md +0 -0
  26. {engin-0.0.8 → engin-0.0.9}/docs/engin.md +0 -0
  27. {engin-0.0.8 → engin-0.0.9}/docs/guides/dependency_injection.md +0 -0
  28. {engin-0.0.8 → engin-0.0.9}/docs/index.md +0 -0
  29. {engin-0.0.8 → engin-0.0.9}/docs/js/readthedocs.js +0 -0
  30. {engin-0.0.8 → engin-0.0.9}/docs/overrides/main.html +0 -0
  31. {engin-0.0.8 → engin-0.0.9}/examples/__init__.py +0 -0
  32. {engin-0.0.8 → engin-0.0.9}/examples/asgi/__init__.py +0 -0
  33. {engin-0.0.8 → engin-0.0.9}/examples/asgi/app.py +0 -0
  34. {engin-0.0.8 → engin-0.0.9}/examples/asgi/common/__init__.py +0 -0
  35. {engin-0.0.8 → engin-0.0.9}/examples/asgi/common/db/__init__.py +0 -0
  36. {engin-0.0.8 → engin-0.0.9}/examples/asgi/common/db/adapaters/__init__.py +0 -0
  37. {engin-0.0.8 → engin-0.0.9}/examples/asgi/common/db/adapaters/memory.py +0 -0
  38. {engin-0.0.8 → engin-0.0.9}/examples/asgi/common/db/block.py +0 -0
  39. {engin-0.0.8 → engin-0.0.9}/examples/asgi/common/db/ports.py +0 -0
  40. {engin-0.0.8 → engin-0.0.9}/examples/asgi/common/starlette/__init__.py +0 -0
  41. {engin-0.0.8 → engin-0.0.9}/examples/asgi/common/starlette/endpoint.py +0 -0
  42. {engin-0.0.8 → engin-0.0.9}/examples/asgi/features/__init__.py +0 -0
  43. {engin-0.0.8 → engin-0.0.9}/examples/asgi/features/cats/__init__.py +0 -0
  44. {engin-0.0.8 → engin-0.0.9}/examples/asgi/features/cats/api/__init__.py +0 -0
  45. {engin-0.0.8 → engin-0.0.9}/examples/asgi/features/cats/api/get.py +0 -0
  46. {engin-0.0.8 → engin-0.0.9}/examples/asgi/features/cats/api/post.py +0 -0
  47. {engin-0.0.8 → engin-0.0.9}/examples/asgi/features/cats/block.py +0 -0
  48. {engin-0.0.8 → engin-0.0.9}/examples/asgi/features/cats/domain.py +0 -0
  49. {engin-0.0.8 → engin-0.0.9}/examples/fastapi/__init__.py +0 -0
  50. {engin-0.0.8 → engin-0.0.9}/examples/fastapi/main.py +0 -0
  51. {engin-0.0.8 → engin-0.0.9}/examples/fastapi/routes/__init__.py +0 -0
  52. {engin-0.0.8 → engin-0.0.9}/examples/fastapi/routes/cats/__init__.py +0 -0
  53. {engin-0.0.8 → engin-0.0.9}/examples/fastapi/routes/cats/adapters/__init__.py +0 -0
  54. {engin-0.0.8 → engin-0.0.9}/examples/fastapi/routes/cats/adapters/repository.py +0 -0
  55. {engin-0.0.8 → engin-0.0.9}/examples/fastapi/routes/cats/api.py +0 -0
  56. {engin-0.0.8 → engin-0.0.9}/examples/fastapi/routes/cats/domain.py +0 -0
  57. {engin-0.0.8 → engin-0.0.9}/examples/fastapi/routes/cats/ports.py +0 -0
  58. {engin-0.0.8 → engin-0.0.9}/examples/simple/__init__.py +0 -0
  59. {engin-0.0.8 → engin-0.0.9}/examples/simple/main.py +0 -0
  60. {engin-0.0.8 → engin-0.0.9}/mkdocs.yaml +0 -0
  61. {engin-0.0.8 → engin-0.0.9}/src/engin/__init__.py +0 -0
  62. {engin-0.0.8 → engin-0.0.9}/src/engin/_assembler.py +0 -0
  63. {engin-0.0.8 → engin-0.0.9}/src/engin/_engin.py +0 -0
  64. {engin-0.0.8 → engin-0.0.9}/src/engin/_exceptions.py +0 -0
  65. {engin-0.0.8 → engin-0.0.9}/src/engin/_lifecycle.py +0 -0
  66. {engin-0.0.8 → engin-0.0.9}/src/engin/_type_utils.py +0 -0
  67. {engin-0.0.8 → engin-0.0.9}/src/engin/ext/__init__.py +0 -0
  68. {engin-0.0.8 → engin-0.0.9}/src/engin/py.typed +0 -0
  69. {engin-0.0.8 → engin-0.0.9}/src/engin/scripts/__init__.py +0 -0
  70. {engin-0.0.8 → engin-0.0.9}/tests/__init__.py +0 -0
  71. {engin-0.0.8 → engin-0.0.9}/tests/acceptance/__init__.py +0 -0
  72. {engin-0.0.8 → engin-0.0.9}/tests/acceptance/test_error_in_shutdown.py +0 -0
  73. {engin-0.0.8 → engin-0.0.9}/tests/acceptance/test_error_in_start_up.py +0 -0
  74. {engin-0.0.8 → engin-0.0.9}/tests/conftest.py +0 -0
  75. {engin-0.0.8 → engin-0.0.9}/tests/deps.py +0 -0
  76. {engin-0.0.8 → engin-0.0.9}/tests/test_assembler.py +0 -0
  77. {engin-0.0.8 → engin-0.0.9}/tests/test_dependencies.py +0 -0
  78. {engin-0.0.8 → engin-0.0.9}/tests/test_engin.py +0 -0
  79. {engin-0.0.8 → engin-0.0.9}/tests/test_modules.py +0 -0
  80. {engin-0.0.8 → engin-0.0.9}/tests/test_utils.py +0 -0
  81. {engin-0.0.8 → engin-0.0.9}/uv.lock +0 -0
@@ -6,6 +6,22 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
8
 
9
+ ## [0.0.9] - 2025-02-22
10
+
11
+ ### Added
12
+
13
+ - Dependency class now has a new attribute: `func_name`.
14
+
15
+ ### Changed
16
+
17
+ - Improved `engin-graph` output.
18
+ - The `module` attribute of dependencies has been renamed to `origin`
19
+
20
+ ### Fixed
21
+
22
+ - Options provided under the `options` on a Block now have the `block_name` set.
23
+
24
+
9
25
  ## [0.0.8] - 2025-02-22
10
26
 
11
27
  ### Added
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: engin
3
- Version: 0.0.8
3
+ Version: 0.0.9
4
4
  Summary: An async-first modular application framework
5
5
  Project-URL: Homepage, https://github.com/invokermain/engin
6
6
  Project-URL: Documentation, https://engin.readthedocs.io/en/latest/
@@ -12,4 +12,6 @@ logging.basicConfig(level=logging.DEBUG)
12
12
 
13
13
  app = ASGIEngin(AppBlock(), DatabaseBlock(), CatBlock(), Supply(AppConfig(debug=True)))
14
14
 
15
- uvicorn.run(app)
15
+
16
+ if __name__ == "__main__":
17
+ uvicorn.run(app)
@@ -0,0 +1,29 @@
1
+ from fastapi import APIRouter, FastAPI
2
+ from pydantic_settings import BaseSettings
3
+
4
+ from engin import Block, provide
5
+
6
+
7
+ class AppConfig(BaseSettings):
8
+ debug: bool = False
9
+
10
+
11
+ class AppBlock(Block):
12
+ @provide
13
+ def default_config(self) -> AppConfig:
14
+ return AppConfig()
15
+
16
+ @provide
17
+ def app_factory(self, app_config: AppConfig, routers: list[APIRouter]) -> FastAPI:
18
+ app = FastAPI(debug=app_config.debug)
19
+
20
+ for router in routers:
21
+ app.include_router(router)
22
+
23
+ app.add_api_route(path="/health", endpoint=_health)
24
+
25
+ return app
26
+
27
+
28
+ async def _health() -> dict[str, bool]:
29
+ return {"ok": True}
@@ -1,16 +1,14 @@
1
- from fastapi import FastAPI
1
+ from typing import ClassVar
2
2
 
3
- from engin import Block, invoke, provide
3
+ from engin import Block, Invoke, Provide, Supply, provide
4
4
  from examples.fastapi.routes.cats.adapters.repository import InMemoryCatRepository
5
5
  from examples.fastapi.routes.cats.api import router
6
6
  from examples.fastapi.routes.cats.ports import CatRepository
7
7
 
8
8
 
9
9
  class CatBlock(Block):
10
+ options: ClassVar[list[Provide | Invoke]] = [Supply([router])]
11
+
10
12
  @provide
11
13
  def cat_repository(self) -> CatRepository:
12
14
  return InMemoryCatRepository()
13
-
14
- @invoke
15
- def attach_router(self, app: FastAPI) -> None:
16
- app.include_router(router)
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "engin"
3
- version = "0.0.8"
3
+ version = "0.0.9"
4
4
  description = "An async-first modular application framework"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10"
@@ -59,6 +59,8 @@ class Block(Iterable[Provide | Invoke]):
59
59
  raise RuntimeError("Block option is not an instance of Provide or Invoke")
60
60
  opt.set_block_name(self._name)
61
61
  self._options.append(opt)
62
+ for opt in self.options:
63
+ opt.set_block_name(self._name)
62
64
 
63
65
  @property
64
66
  def name(self) -> str:
@@ -31,13 +31,23 @@ class Dependency(ABC, Generic[P, T]):
31
31
  self._block_name = block_name
32
32
 
33
33
  @property
34
- def module(self) -> str:
34
+ def origin(self) -> str:
35
+ """
36
+ The module that this Dependency originated from.
37
+
38
+ Returns:
39
+ A string, e.g. "examples.fastapi.app"
40
+ """
35
41
  return self._func.__module__
36
42
 
37
43
  @property
38
44
  def block_name(self) -> str | None:
39
45
  return self._block_name
40
46
 
47
+ @property
48
+ def func_name(self) -> str:
49
+ return self._func.__name__
50
+
41
51
  @property
42
52
  def name(self) -> str:
43
53
  if self._block_name:
@@ -105,6 +115,10 @@ class Entrypoint(Invoke):
105
115
  self._type = type_
106
116
  super().__init__(invocation=_noop, block_name=block_name)
107
117
 
118
+ @property
119
+ def origin(self) -> str:
120
+ return self._type.__module__
121
+
108
122
  @property
109
123
  def parameter_types(self) -> list[TypeId]:
110
124
  return [type_id_of(self._type)]
@@ -172,6 +186,10 @@ class Supply(Provide, Generic[T]):
172
186
  self._get_val.__annotations__["return"] = type_hint
173
187
  super().__init__(builder=self._get_val, block_name=block_name)
174
188
 
189
+ @property
190
+ def origin(self) -> str:
191
+ return self._value.__module__
192
+
175
193
  @property
176
194
  def return_type(self) -> type[T]:
177
195
  if self._type_hint is not None:
@@ -0,0 +1,50 @@
1
+ from collections.abc import Iterable
2
+ from dataclasses import dataclass
3
+
4
+ from engin import Provide
5
+ from engin._dependency import Dependency
6
+ from engin._type_utils import TypeId
7
+
8
+
9
+ @dataclass(slots=True, frozen=True, kw_only=True)
10
+ class Node:
11
+ """
12
+ A Node in the Dependency Graph.
13
+ """
14
+
15
+ node: Dependency
16
+ parent: Dependency | None
17
+
18
+ def __repr__(self) -> str:
19
+ return f"Node(node={self.node!s},parent={self.parent!s})"
20
+
21
+
22
+ class DependencyGrapher:
23
+ def __init__(self, providers: dict[TypeId, Provide | list[Provide]]) -> None:
24
+ self._providers: dict[TypeId, Provide | list[Provide]] = providers
25
+
26
+ def resolve(self, roots: Iterable[Dependency]) -> list[Node]:
27
+ return self._resolve_recursive(roots, seen=set())
28
+
29
+ def _resolve_recursive(
30
+ self, roots: Iterable[Dependency], *, seen: set[TypeId]
31
+ ) -> list[Node]:
32
+ nodes: list[Node] = []
33
+ for root in roots:
34
+ for parameter in root.parameter_types:
35
+ provider = self._providers[parameter]
36
+
37
+ # multiprovider
38
+ if isinstance(provider, list):
39
+ nodes.extend(Node(node=p, parent=root) for p in provider)
40
+ if parameter not in seen:
41
+ nodes.extend(self._resolve_recursive(provider, seen=seen))
42
+ # single provider
43
+ else:
44
+ nodes.append(Node(node=provider, parent=root))
45
+ if parameter not in seen:
46
+ nodes.extend(self._resolve_recursive([provider], seen=seen))
47
+
48
+ seen.add(parameter)
49
+
50
+ return nodes
@@ -2,10 +2,11 @@ import traceback
2
2
  from collections.abc import Awaitable, Callable, MutableMapping
3
3
  from typing import Any, ClassVar, Protocol, TypeAlias
4
4
 
5
- from engin import Engin, Option
5
+ from engin import Engin, Entrypoint, Option
6
6
 
7
7
  __all__ = ["ASGIEngin", "ASGIType"]
8
8
 
9
+ from engin._graph import DependencyGrapher, Node
9
10
 
10
11
  _Scope: TypeAlias = MutableMapping[str, Any]
11
12
  _Message: TypeAlias = MutableMapping[str, Any]
@@ -49,6 +50,10 @@ class ASGIEngin(Engin, ASGIType):
49
50
  await self.start()
50
51
  self._asgi_app = await self._assembler.get(self._asgi_type)
51
52
 
53
+ def graph(self) -> list[Node]:
54
+ grapher = DependencyGrapher({**self._providers, **self._multiproviders})
55
+ return grapher.resolve([Entrypoint(self._asgi_type), *self._invocations])
56
+
52
57
 
53
58
  class _Rereceive:
54
59
  def __init__(self, message: _Message) -> None:
@@ -0,0 +1,168 @@
1
+ import inspect
2
+ import typing
3
+ from collections.abc import Iterable
4
+ from inspect import Parameter
5
+ from typing import ClassVar, TypeVar
6
+
7
+ from fastapi.routing import APIRoute
8
+
9
+ from engin import Engin, Entrypoint, Invoke, Option
10
+ from engin._dependency import Dependency, Supply
11
+ from engin._graph import DependencyGrapher, Node
12
+ from engin._type_utils import TypeId, type_id_of
13
+ from engin.ext.asgi import ASGIEngin
14
+
15
+ try:
16
+ from fastapi import APIRouter, FastAPI
17
+ from fastapi.params import Depends
18
+ from starlette.requests import HTTPConnection
19
+ except ImportError as err:
20
+ raise ImportError(
21
+ "fastapi package must be installed to use the fastapi extension"
22
+ ) from err
23
+
24
+ __all__ = ["APIRouteDependency", "FastAPIEngin", "Inject"]
25
+
26
+
27
+ def _attach_engin(
28
+ app: FastAPI,
29
+ engin: Engin,
30
+ ) -> None:
31
+ app.state.engin = engin
32
+
33
+
34
+ class FastAPIEngin(ASGIEngin):
35
+ _LIB_OPTIONS: ClassVar[list[Option]] = [*ASGIEngin._LIB_OPTIONS, Invoke(_attach_engin)]
36
+ _asgi_type = FastAPI
37
+
38
+ def graph(self) -> list[Node]:
39
+ grapher = _FastAPIDependencyGrapher({**self._providers, **self._multiproviders})
40
+ return grapher.resolve(
41
+ [
42
+ Entrypoint(self._asgi_type),
43
+ *[i for i in self._invocations if i.func_name != "_attach_engin"],
44
+ ]
45
+ )
46
+
47
+
48
+ T = TypeVar("T")
49
+
50
+
51
+ def Inject(interface: type[T]) -> Depends:
52
+ async def inner(conn: HTTPConnection) -> T:
53
+ engin: Engin = conn.app.state.engin
54
+ return await engin.assembler.get(interface)
55
+
56
+ dep = Depends(inner)
57
+ dep.__engin__ = True # type: ignore[attr-defined]
58
+ return dep
59
+
60
+
61
+ class _FastAPIDependencyGrapher(DependencyGrapher):
62
+ """
63
+ This exists in order to bridge the gap between
64
+ """
65
+
66
+ def _resolve_recursive(
67
+ self, roots: Iterable[Dependency], *, seen: set[TypeId]
68
+ ) -> list[Node]:
69
+ nodes: list[Node] = []
70
+ for root in roots:
71
+ for parameter in root.parameter_types:
72
+ provider = self._providers[parameter]
73
+
74
+ # multiprovider
75
+ if isinstance(provider, list):
76
+ for p in provider:
77
+ nodes.append(Node(node=p, parent=root))
78
+
79
+ if isinstance(p, Supply):
80
+ route_dependencies = _extract_routes_from_supply(p)
81
+ nodes.extend(
82
+ Node(node=route_dependency, parent=p)
83
+ for route_dependency in route_dependencies
84
+ )
85
+ nodes.extend(
86
+ self._resolve_recursive(route_dependencies, seen=seen)
87
+ )
88
+
89
+ if parameter not in seen:
90
+ nodes.extend(self._resolve_recursive(provider, seen=seen))
91
+ # single provider
92
+ else:
93
+ nodes.append(Node(node=provider, parent=root))
94
+ # not sure why anyone would ever supply a single APIRouter in an
95
+ # application, but just in case
96
+ if isinstance(provider, Supply):
97
+ route_dependencies = _extract_routes_from_supply(provider)
98
+ nodes.extend(
99
+ Node(node=route_dependency, parent=provider)
100
+ for route_dependency in route_dependencies
101
+ )
102
+ nodes.extend(self._resolve_recursive(route_dependencies, seen=seen))
103
+ if parameter not in seen:
104
+ nodes.extend(self._resolve_recursive([provider], seen=seen))
105
+
106
+ seen.add(parameter)
107
+
108
+ return nodes
109
+
110
+
111
+ def _extract_routes_from_supply(supply: Supply) -> list[Dependency]:
112
+ if supply.is_multiprovider:
113
+ inner = supply._value[0]
114
+ if isinstance(inner, APIRouter):
115
+ return [
116
+ APIRouteDependency(route, block_name=supply.block_name)
117
+ for route in inner.routes
118
+ if isinstance(route, APIRoute)
119
+ ]
120
+ return []
121
+
122
+
123
+ class APIRouteDependency(Dependency):
124
+ """
125
+ This is a pseudo-dependency that is only used when calling FastAPIEngin.graph() in
126
+ order to provide richer metadata to the Node.
127
+
128
+ This class should never be constructed in application code.
129
+ """
130
+
131
+ def __init__(self, route: APIRoute, block_name: str | None = None) -> None:
132
+ """
133
+ Warning: this should never be constructed in application code.
134
+ """
135
+ self._route = route
136
+ self._signature = inspect.signature(route.endpoint)
137
+ self._block_name = block_name
138
+
139
+ @property
140
+ def route(self) -> APIRoute:
141
+ return self._route
142
+
143
+ @property
144
+ def parameter_types(self) -> list[TypeId]:
145
+ parameters = list(self._signature.parameters.values())
146
+ if not parameters:
147
+ return []
148
+ if parameters[0].name == "self":
149
+ parameters.pop(0)
150
+ return [
151
+ type_id_of(typing.get_args(param.annotation)[0])
152
+ for param in parameters
153
+ if self._is_injected_param(param)
154
+ ]
155
+
156
+ @staticmethod
157
+ def _is_injected_param(param: Parameter) -> bool:
158
+ if typing.get_origin(param.annotation) != typing.Annotated:
159
+ return False
160
+ args = typing.get_args(param.annotation)
161
+ if len(args) != 2:
162
+ return False
163
+ return isinstance(args[1], Depends) and hasattr(args[1], "__engin__")
164
+
165
+ @property
166
+ def name(self) -> str:
167
+ methods = ",".join(self._route.methods)
168
+ return f"{methods} {self._route.path}"
@@ -8,8 +8,10 @@ from http.server import BaseHTTPRequestHandler
8
8
  from time import sleep
9
9
  from typing import Any
10
10
 
11
- from engin import Engin
12
- from engin._dependency import Dependency, Provide
11
+ from engin import Engin, Entrypoint, Invoke
12
+ from engin._dependency import Dependency, Provide, Supply
13
+ from engin.ext.asgi import ASGIEngin
14
+ from engin.ext.fastapi import APIRouteDependency
13
15
 
14
16
  # mute logging from importing of files + engin's debug logging.
15
17
  logging.disable()
@@ -18,9 +20,6 @@ args = ArgumentParser(
18
20
  prog="engin-graph",
19
21
  description="Creates a visualisation of your application's dependencies",
20
22
  )
21
- args.add_argument(
22
- "-e", "--exclude", help="a list of packages or module to exclude", default=["engin"]
23
- )
24
23
  args.add_argument(
25
24
  "app",
26
25
  help=(
@@ -37,7 +36,6 @@ def serve_graph() -> None:
37
36
  parsed = args.parse_args()
38
37
 
39
38
  app = parsed.app
40
- excluded_modules = parsed.exclude
41
39
 
42
40
  try:
43
41
  module_name, engin_name = app.split(":", maxsplit=1)
@@ -60,13 +58,19 @@ def serve_graph() -> None:
60
58
 
61
59
  # transform dependencies into mermaid syntax
62
60
  dependencies = [
63
- f"{_render_node(node['parent'])} --> {_render_node(node['node'])}"
61
+ f"{_render_node(node.parent)} --> {_render_node(node.node)}"
64
62
  for node in nodes
65
- if node["parent"] is not None
66
- and not _should_exclude(node["node"].module, excluded_modules)
63
+ if node.parent is not None
67
64
  ]
68
65
 
69
- html = _GRAPH_HTML.replace("%%DATA%%", "\n".join(dependencies)).encode("utf8")
66
+ html = (
67
+ _GRAPH_HTML.replace("%%DATA%%", "\n".join(dependencies))
68
+ .replace(
69
+ "%%LEGEND%%",
70
+ ASGI_ENGIN_LEGEND if isinstance(instance, ASGIEngin) else DEFAULT_LEGEND,
71
+ )
72
+ .encode("utf8")
73
+ )
70
74
 
71
75
  class Handler(BaseHTTPRequestHandler):
72
76
  def do_GET(self) -> None:
@@ -93,24 +97,66 @@ def serve_graph() -> None:
93
97
  print("Exiting the server...")
94
98
 
95
99
 
100
+ _BLOCK_IDX: dict[str, int] = {}
101
+ _SEEN_BLOCKS: list[str] = []
102
+
103
+
96
104
  def _render_node(node: Dependency) -> str:
105
+ node_id = id(node)
106
+ md = ""
107
+ style = ""
108
+
109
+ # format block name
110
+ if n := node.block_name:
111
+ md += f"_{n}_\n"
112
+ if n not in _BLOCK_IDX:
113
+ _BLOCK_IDX[n] = len(_SEEN_BLOCKS) % 8
114
+ _SEEN_BLOCKS.append(n)
115
+ style = f":::b{_BLOCK_IDX[n]}"
116
+
117
+ if isinstance(node, Supply):
118
+ md += f"{node.return_type_id}"
119
+ return f'{node_id}("`{md}`"){style}'
97
120
  if isinstance(node, Provide):
98
- return str(node.return_type_id)
121
+ md += f"{node.return_type_id}"
122
+ return f'{node_id}["`{md}`"]{style}'
123
+ if isinstance(node, Entrypoint):
124
+ entrypoint_type = node.parameter_types[0]
125
+ md += f"{entrypoint_type}"
126
+ return f'{node_id}[/"`{md}`"\\]{style}'
127
+ if isinstance(node, Invoke):
128
+ md += f"{node.func_name}"
129
+ return f'{node_id}[/"`{md}`"/]{style}'
130
+ if isinstance(node, APIRouteDependency):
131
+ md += f"{node.name}"
132
+ return f'{node_id}[["`{md}`"]]{style}'
99
133
  else:
100
- return node.name
101
-
102
-
103
- def _should_exclude(module: str, excluded: list[str]) -> bool:
104
- return any(module.startswith(e) for e in excluded)
134
+ return f'{node_id}["`{node.name}`"]{style}'
105
135
 
106
136
 
107
137
  _GRAPH_HTML = """
108
138
  <!doctype html>
109
139
  <html lang="en">
110
140
  <body>
141
+ <div style="border-style:outset">
142
+ <p>LEGEND</p>
143
+ <pre class="mermaid">
144
+ graph LR
145
+ %%LEGEND%%
146
+ classDef b0 fill:#7fc97f;
147
+ </pre>
148
+ </div>
111
149
  <pre class="mermaid">
112
150
  graph TD
113
151
  %%DATA%%
152
+ classDef b0 fill:#7fc97f;
153
+ classDef b1 fill:#beaed4;
154
+ classDef b2 fill:#fdc086;
155
+ classDef b3 fill:#ffff99;
156
+ classDef b4 fill:#386cb0;
157
+ classDef b5 fill:#f0027f;
158
+ classDef b6 fill:#bf5b17;
159
+ classDef b7 fill:#666666;
114
160
  </pre>
115
161
  <script type="module">
116
162
  import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs';
@@ -120,3 +166,9 @@ _GRAPH_HTML = """
120
166
  </body>
121
167
  </html>
122
168
  """
169
+
170
+ DEFAULT_LEGEND = (
171
+ "0[/Invoke/] ~~~ 1[/Entrypoint\\] ~~~ 2[Provide] ~~~ 3(Supply)"
172
+ ' ~~~ 4["`Block Grouping`"]:::b0'
173
+ )
174
+ ASGI_ENGIN_LEGEND = DEFAULT_LEGEND + " ~~~ 5[[API Route]]"
@@ -1,25 +0,0 @@
1
- from fastapi import FastAPI
2
- from pydantic_settings import BaseSettings
3
-
4
- from engin import Block, invoke, provide
5
-
6
-
7
- class AppConfig(BaseSettings):
8
- debug: bool = False
9
-
10
-
11
- class AppBlock(Block):
12
- @provide
13
- def app_factory(self, app_config: AppConfig) -> FastAPI:
14
- return FastAPI(debug=app_config.debug)
15
-
16
- @provide
17
- def default_config(self) -> AppConfig:
18
- return AppConfig()
19
-
20
- @invoke
21
- def add_health_endpoint(self, app: FastAPI) -> None:
22
- async def health() -> dict[str, bool]:
23
- return {"ok": True}
24
-
25
- app.add_api_route(path="/health", endpoint=health)
@@ -1,39 +0,0 @@
1
- from collections.abc import Iterable
2
- from typing import TypedDict
3
-
4
- from engin._dependency import Dependency, Provide
5
- from engin._type_utils import TypeId
6
-
7
-
8
- class Node(TypedDict):
9
- node: Dependency
10
- parent: Dependency | None
11
-
12
-
13
- class DependencyGrapher:
14
- def __init__(self, providers: dict[TypeId, Provide | list[Provide]]) -> None:
15
- self._providers: dict[TypeId, Provide | list[Provide]] = providers
16
-
17
- def resolve(self, roots: Iterable[Dependency]) -> list[Node]:
18
- seen: set[TypeId] = set()
19
- nodes: list[Node] = []
20
-
21
- for root in roots:
22
- for parameter in root.parameter_types:
23
- if parameter in seen:
24
- continue
25
-
26
- seen.add(parameter)
27
- provider = self._providers[parameter]
28
-
29
- # multiprovider
30
- if isinstance(provider, list):
31
- for p in provider:
32
- nodes.append({"node": p, "parent": root})
33
- nodes.extend(self.resolve([p]))
34
- # single provider
35
- else:
36
- nodes.append({"node": provider, "parent": root})
37
- nodes.extend(self.resolve([provider]))
38
-
39
- return nodes
@@ -1,38 +0,0 @@
1
- from typing import ClassVar, TypeVar
2
-
3
- from engin import Engin, Invoke, Option
4
- from engin.ext.asgi import ASGIEngin
5
-
6
- try:
7
- from fastapi import FastAPI
8
- from fastapi.params import Depends
9
- from starlette.requests import HTTPConnection
10
- except ImportError as err:
11
- raise ImportError(
12
- "fastapi package must be installed to use the fastapi extension"
13
- ) from err
14
-
15
- __all__ = ["FastAPIEngin", "Inject"]
16
-
17
-
18
- def _attach_engin(
19
- app: FastAPI,
20
- engin: Engin,
21
- ) -> None:
22
- app.state.engin = engin
23
-
24
-
25
- class FastAPIEngin(ASGIEngin):
26
- _LIB_OPTIONS: ClassVar[list[Option]] = [*ASGIEngin._LIB_OPTIONS, Invoke(_attach_engin)]
27
- _asgi_type = FastAPI
28
-
29
-
30
- T = TypeVar("T")
31
-
32
-
33
- def Inject(interface: type[T]) -> Depends:
34
- async def inner(conn: HTTPConnection) -> T:
35
- engin: Engin = conn.app.state.engin
36
- return await engin.assembler.get(interface)
37
-
38
- return Depends(inner)
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes