Skip to content

Add register_middleware hook #50

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions fps/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,51 @@ def _load_routers(app: FastAPI) -> None:
logger.info("No plugin API router to load")


def _load_middlewares(app: FastAPI) -> None:

pm = _get_pluggin_manager(HookType.MIDDLEWARE)

grouped_middlewares = _grouped_hookimpls_results(pm.hook.middleware)

if grouped_middlewares:

pkg_names = {get_pkg_name(p, strip_fps=False) for p in grouped_middlewares}
logger.info(f"Loading middlewares from plugin package(s) {pkg_names}")

for p, middlewares in grouped_middlewares.items():
p_name = Config.plugin_name(p)
plugin_config = Config.from_name(p_name)

disabled = (
plugin_config
and not plugin_config.enabled
or p_name in Config(FPSConfig).disabled_plugins
or (
Config(FPSConfig).enabled_plugins
and p_name not in Config(FPSConfig).enabled_plugins
)
or p_name not in Config(FPSConfig).middlewares
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the order of middlewares is not guaranteed here
I think you need to :

  • collect middlewares from enabled plugins
  • check middlewares listed in FPS config are found
  • add them on the app in the config order

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm wondering if the middlewares config should specify plugins, or middlewares inside plugins?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems natural to let each plugin specify its middlewares' order, and thus the middlewares config should rather specify plugins, but it looks like the middlewares' order we get in grouped_middlewares doesn't respect the registration order.

)
if not middlewares or disabled:
disabled_msg = " (disabled)" if disabled else ""
logger.info(
f"No middleware registered for plugin '{p_name}'{disabled_msg}"
)
continue

for plugin_middleware, plugin_kwargs in middlewares:
app.add_middleware(
plugin_middleware,
**plugin_kwargs,
)

logger.info(
f"{len(middlewares)} middleware(s) added from plugin '{p_name}'"
)
else:
logger.info("No plugin middleware to load")


def create_app():

logging.getLogger("fps")
Expand All @@ -283,6 +328,7 @@ def create_app():

_load_routers(app)
_load_exceptions_handlers(app)
_load_middlewares(app)

Config.check_not_used_sections()

Expand Down
5 changes: 4 additions & 1 deletion fps/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,10 @@ class FPSConfig(BaseModel):
enabled_plugins: List[str] = []
disabled_plugins: List[str] = []

@validator("enabled_plugins", "disabled_plugins")
# plugin middlewares
middlewares: List[str] = []

@validator("enabled_plugins", "disabled_plugins", "middlewares")
def plugins_format(cls, plugins):
warnings = [p for p in plugins if p.startswith("[") or p.endswith("]")]
if warnings:
Expand Down
15 changes: 15 additions & 0 deletions fps/hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ class HookType(Enum):
ROUTER = "fps_router"
CONFIG = "fps_config"
EXCEPTION = "fps_exception"
MIDDLEWARE = "fps_middleware"


@pluggy.HookspecMarker(HookType.ROUTER.value)
Expand Down Expand Up @@ -75,3 +76,17 @@ def plugin_name_callback() -> str:
return pluggy.HookimplMarker(HookType.CONFIG.value)(
function=plugin_name_callback, specname="plugin_name"
)


@pluggy.HookspecMarker(HookType.MIDDLEWARE.value)
def middleware() -> Tuple[type, Dict[str, Any]]:
pass


def register_middleware(m: type, **kwargs: Dict[str, Any]):
def middleware_callback() -> Tuple[type, Dict[str, Any]]:
return m, kwargs

return pluggy.HookimplMarker(HookType.MIDDLEWARE.value)(
function=middleware_callback, specname="middleware"
)