Skip to content

Commit

Permalink
Add before_routing for Reverse Proxy plugins (#1252)
Browse files Browse the repository at this point in the history
* Add `before_routing` for Reverse Proxy plugins

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
abhinavsingh and pre-commit-ci[bot] authored Aug 11, 2022
1 parent be771d4 commit eed67ad
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
8 changes: 7 additions & 1 deletion proxy/http/server/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Any, Dict, List, Tuple, Union, Optional

from proxy.http.url import Url
from ..parser import HttpParser
from ...http.url import Url
from ..responses import NOT_FOUND_RESPONSE_PKT, okResponse
from ..websocket import WebsocketFrame
from ..connection import HttpClientConnection
Expand Down Expand Up @@ -161,6 +161,12 @@ def routes(self) -> List[Union[str, Tuple[str, List[bytes]]]]:
must return the url to serve."""
raise NotImplementedError() # pragma: no cover

def before_routing(self, request: HttpParser) -> Optional[HttpParser]:
"""Plugins can modify request, return response, close connection.
If None is returned, request will be dropped and closed."""
return request # pragma: no cover

def handle_route(self, request: HttpParser, pattern: RePattern) -> Url:
"""Implement this method if you have configured dynamic routes."""
pass
Expand Down
11 changes: 11 additions & 0 deletions proxy/http/server/reverse.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ def __init__(self, *args: Any, **kwargs: Any):
self.plugins.append(plugin)

def handle_upstream_data(self, raw: memoryview) -> None:
# TODO: Parse response and implement plugin hook per parsed response object
# This will give plugins a chance to modify the responses before dispatching to client
self.client.queue(raw)

def routes(self) -> List[Tuple[int, str]]:
Expand All @@ -57,6 +59,14 @@ def routes(self) -> List[Tuple[int, str]]:
return r

def handle_request(self, request: HttpParser) -> None:
# before_routing
for plugin in self.plugins:
r = plugin.before_routing(request)
if r is None:
raise HttpProtocolException('before_routing closed connection')
request = r

# routes
for plugin in self.plugins:
for route in plugin.routes():
if isinstance(route, tuple):
Expand All @@ -73,6 +83,7 @@ def handle_request(self, request: HttpParser) -> None:
break
else:
raise ValueError('Invalid route')

assert self.choice and self.choice.hostname
port = self.choice.port or \
DEFAULT_HTTP_PORT \
Expand Down

0 comments on commit eed67ad

Please sign in to comment.