Skip to content

Commit 6c21e34

Browse files
[Flags] min_compression_length consistency (#1061)
* `min_compression_length` consistency, it was used as `min_compression_limit` at a few places * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * revert back web server route * Move `serve_static_file` as a staticmethod within web plugin base Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent ee424ac commit 6c21e34

File tree

6 files changed

+47
-41
lines changed

6 files changed

+47
-41
lines changed

proxy/common/constants.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ def _env_threadless_compliant() -> bool:
125125
DEFAULT_PORT = 8899
126126
DEFAULT_SERVER_RECVBUF_SIZE = DEFAULT_BUFFER_SIZE
127127
DEFAULT_STATIC_SERVER_DIR = os.path.join(PROXY_PY_DIR, "public")
128-
DEFAULT_MIN_COMPRESSION_LIMIT = 20 # In bytes
128+
DEFAULT_MIN_COMPRESSION_LENGTH = 20 # In bytes
129129
DEFAULT_THREADLESS = _env_threadless_compliant()
130130
DEFAULT_LOCAL_EXECUTOR = True
131131
DEFAULT_TIMEOUT = 10.0

proxy/common/flag.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
PLUGIN_REVERSE_PROXY, DEFAULT_NUM_ACCEPTORS, PLUGIN_INSPECT_TRAFFIC,
3131
DEFAULT_DISABLE_HEADERS, PY2_DEPRECATION_MESSAGE, DEFAULT_DEVTOOLS_WS_PATH,
3232
PLUGIN_DEVTOOLS_PROTOCOL, PLUGIN_WEBSOCKET_TRANSPORT,
33-
DEFAULT_DATA_DIRECTORY_PATH, DEFAULT_MIN_COMPRESSION_LIMIT,
33+
DEFAULT_DATA_DIRECTORY_PATH, DEFAULT_MIN_COMPRESSION_LENGTH,
3434
)
3535

3636

@@ -335,13 +335,13 @@ def initialize(
335335
args.static_server_dir,
336336
),
337337
)
338-
args.min_compression_limit = cast(
338+
args.min_compression_length = cast(
339339
bool,
340340
opts.get(
341-
'min_compression_limit',
341+
'min_compression_length',
342342
getattr(
343-
args, 'min_compression_limit',
344-
DEFAULT_MIN_COMPRESSION_LIMIT,
343+
args, 'min_compression_length',
344+
DEFAULT_MIN_COMPRESSION_LENGTH,
345345
),
346346
),
347347
)

proxy/dashboard/dashboard.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,7 @@
1313
from typing import List, Tuple
1414

1515
from ..http.parser import HttpParser
16-
from ..http.server import (
17-
HttpWebServerPlugin, HttpWebServerBasePlugin, httpProtocolTypes,
18-
)
16+
from ..http.server import HttpWebServerBasePlugin, httpProtocolTypes
1917
from ..http.responses import permanentRedirectResponse
2018

2119

@@ -46,11 +44,12 @@ def routes(self) -> List[Tuple[int, str]]:
4644
def handle_request(self, request: HttpParser) -> None:
4745
if request.path == b'/dashboard/':
4846
self.client.queue(
49-
HttpWebServerPlugin.read_and_build_static_file_response(
47+
self.serve_static_file(
5048
os.path.join(
5149
self.flags.static_server_dir,
5250
'dashboard', 'proxy.html',
5351
),
52+
self.flags.min_compression_length,
5453
),
5554
)
5655
elif request.path in (

proxy/http/responses.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,11 @@
1212
from typing import Any, Dict, Optional
1313

1414
from .codes import httpStatusCodes
15-
from ..common.flag import flags
1615
from ..common.utils import build_http_response
17-
from ..common.constants import PROXY_AGENT_HEADER_KEY, PROXY_AGENT_HEADER_VALUE
16+
from ..common.constants import (
17+
PROXY_AGENT_HEADER_KEY, PROXY_AGENT_HEADER_VALUE,
18+
DEFAULT_MIN_COMPRESSION_LENGTH,
19+
)
1820

1921

2022
PROXY_TUNNEL_ESTABLISHED_RESPONSE_PKT = memoryview(
@@ -98,10 +100,11 @@ def okResponse(
98100
content: Optional[bytes] = None,
99101
headers: Optional[Dict[bytes, bytes]] = None,
100102
compress: bool = True,
103+
min_compression_length: int = DEFAULT_MIN_COMPRESSION_LENGTH,
101104
**kwargs: Any,
102105
) -> memoryview:
103106
do_compress: bool = False
104-
if flags.args and compress and content and len(content) > flags.args.min_compression_limit:
107+
if compress and content and len(content) > min_compression_length:
105108
do_compress = True
106109
if not headers:
107110
headers = {}

proxy/http/server/plugin.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,17 @@
99
:license: BSD, see LICENSE for more details.
1010
"""
1111
import argparse
12+
import mimetypes
1213
from abc import ABC, abstractmethod
1314
from typing import TYPE_CHECKING, Any, Dict, List, Tuple, Optional
1415

1516
from ..parser import HttpParser
17+
from ..responses import NOT_FOUND_RESPONSE_PKT, okResponse
1618
from ..websocket import WebsocketFrame
1719
from ..connection import HttpClientConnection
1820
from ...core.event import EventQueue
1921
from ..descriptors import DescriptorsHandlerMixin
22+
from ...common.utils import bytes_
2023

2124

2225
if TYPE_CHECKING: # pragma: no cover
@@ -40,6 +43,28 @@ def __init__(
4043
self.event_queue = event_queue
4144
self.upstream_conn_pool = upstream_conn_pool
4245

46+
@staticmethod
47+
def serve_static_file(path: str, min_compression_length: int) -> memoryview:
48+
try:
49+
with open(path, 'rb') as f:
50+
content = f.read()
51+
content_type = mimetypes.guess_type(path)[0]
52+
if content_type is None:
53+
content_type = 'text/plain'
54+
headers = {
55+
b'Content-Type': bytes_(content_type),
56+
b'Cache-Control': b'max-age=86400',
57+
}
58+
return okResponse(
59+
content=content,
60+
headers=headers,
61+
min_compression_length=min_compression_length,
62+
# TODO: Should we really close or take advantage of keep-alive?
63+
conn_close=True,
64+
)
65+
except FileNotFoundError:
66+
return NOT_FOUND_RESPONSE_PKT
67+
4368
def name(self) -> str:
4469
"""A unique name for your plugin.
4570

proxy/http/server/web.py

Lines changed: 7 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
import time
1313
import socket
1414
import logging
15-
import mimetypes
1615
from typing import Any, Dict, List, Tuple, Union, Pattern, Optional
1716

1817
from .plugin import HttpWebServerBasePlugin
@@ -21,15 +20,15 @@
2120
from .protocols import httpProtocolTypes
2221
from ..exception import HttpProtocolException
2322
from ..protocols import httpProtocols
24-
from ..responses import NOT_FOUND_RESPONSE_PKT, okResponse
23+
from ..responses import NOT_FOUND_RESPONSE_PKT
2524
from ..websocket import WebsocketFrame, websocketOpcodes
2625
from ...common.flag import flags
2726
from ...common.types import Readables, Writables, Descriptors
28-
from ...common.utils import text_, bytes_, build_websocket_handshake_response
27+
from ...common.utils import text_, build_websocket_handshake_response
2928
from ...common.constants import (
3029
DEFAULT_ENABLE_WEB_SERVER, DEFAULT_STATIC_SERVER_DIR,
3130
DEFAULT_ENABLE_REVERSE_PROXY, DEFAULT_ENABLE_STATIC_SERVER,
32-
DEFAULT_MIN_COMPRESSION_LIMIT, DEFAULT_WEB_ACCESS_LOG_FORMAT,
31+
DEFAULT_WEB_ACCESS_LOG_FORMAT, DEFAULT_MIN_COMPRESSION_LENGTH,
3332
)
3433

3534

@@ -65,8 +64,8 @@
6564
flags.add_argument(
6665
'--min-compression-length',
6766
type=int,
68-
default=DEFAULT_MIN_COMPRESSION_LIMIT,
69-
help='Default: ' + str(DEFAULT_MIN_COMPRESSION_LIMIT) + ' bytes. ' +
67+
default=DEFAULT_MIN_COMPRESSION_LENGTH,
68+
help='Default: ' + str(DEFAULT_MIN_COMPRESSION_LENGTH) + ' bytes. ' +
7069
'Sets the minimum length of a response that will be compressed (gzipped).',
7170
)
7271

@@ -124,27 +123,6 @@ def encryption_enabled(self) -> bool:
124123
return self.flags.keyfile is not None and \
125124
self.flags.certfile is not None
126125

127-
@staticmethod
128-
def read_and_build_static_file_response(path: str) -> memoryview:
129-
try:
130-
with open(path, 'rb') as f:
131-
content = f.read()
132-
content_type = mimetypes.guess_type(path)[0]
133-
if content_type is None:
134-
content_type = 'text/plain'
135-
headers = {
136-
b'Content-Type': bytes_(content_type),
137-
b'Cache-Control': b'max-age=86400',
138-
}
139-
return okResponse(
140-
content=content,
141-
headers=headers,
142-
# TODO: Should we really close or take advantage of keep-alive?
143-
conn_close=True,
144-
)
145-
except FileNotFoundError:
146-
return NOT_FOUND_RESPONSE_PKT
147-
148126
def switch_to_websocket(self) -> None:
149127
self.client.queue(
150128
memoryview(
@@ -309,7 +287,8 @@ def _try_route(self, path: bytes) -> bool:
309287
def _try_static_or_404(self, path: bytes) -> None:
310288
path = text_(path).split('?', 1)[0]
311289
self.client.queue(
312-
self.read_and_build_static_file_response(
290+
HttpWebServerBasePlugin.serve_static_file(
313291
self.flags.static_server_dir + path,
292+
self.flags.min_compression_length,
314293
),
315294
)

0 commit comments

Comments
 (0)