From 9fbe0358f54f2ccd1f4109c53acb75ff84e635a1 Mon Sep 17 00:00:00 2001 From: cle-b Date: Sat, 16 Aug 2025 09:32:54 +0200 Subject: [PATCH 1/2] typing list, tuple, dict --- httpdbg/args.py | 3 +- httpdbg/hooks/all.py | 6 +- httpdbg/hooks/external.py | 3 +- httpdbg/hooks/fastapi.py | 5 +- httpdbg/hooks/flask.py | 7 +-- httpdbg/hooks/generic.py | 11 ++-- httpdbg/hooks/h2.py | 117 +++++++++++++++++++++++++++++++++++ httpdbg/hooks/record.py | 10 ++- httpdbg/hooks/recordhttp1.py | 9 ++- httpdbg/hooks/socket.py | 12 ++-- httpdbg/initiator.py | 12 ++-- httpdbg/mode_console.py | 3 +- httpdbg/mode_module.py | 3 +- httpdbg/mode_script.py | 3 +- httpdbg/preview.py | 8 +-- httpdbg/records.py | 14 ++--- httpdbg/utils.py | 9 ++- httpdbg/webapp/api.py | 7 +-- 18 files changed, 170 insertions(+), 72 deletions(-) create mode 100644 httpdbg/hooks/h2.py diff --git a/httpdbg/args.py b/httpdbg/args.py index e43bb47..f44affa 100644 --- a/httpdbg/args.py +++ b/httpdbg/args.py @@ -1,12 +1,11 @@ # -*- coding: utf-8 -*- import argparse from pathlib import Path -from typing import List, Tuple from httpdbg.log import LogLevel -def read_args(args: List[str]) -> Tuple[argparse.Namespace, List[str]]: +def read_args(args: list[str]) -> tuple[argparse.Namespace, list[str]]: httpdbg_args = args client_args = [] for action in ["--console", "--module", "-m", "--script"]: diff --git a/httpdbg/hooks/all.py b/httpdbg/hooks/all.py index 78e4407..9b3aed1 100644 --- a/httpdbg/hooks/all.py +++ b/httpdbg/hooks/all.py @@ -1,8 +1,6 @@ # -*- coding: utf-8 -*- from contextlib import contextmanager from typing import Generator -from typing import List -from typing import Tuple from typing import Union from httpdbg.hooks.aiohttp import hook_aiohttp @@ -26,10 +24,10 @@ @contextmanager def httprecord( records: HTTPRecords = None, - initiators: Union[List[str], None] = None, + initiators: Union[list[str], None] = None, client: bool = True, server: bool = False, - ignore: Tuple[Tuple[str, int], ...] = (), + ignore: tuple[tuple[str, int], ...] = (), multiprocess: bool = True, ) -> Generator[HTTPRecords, None, None]: if records is None: diff --git a/httpdbg/hooks/external.py b/httpdbg/hooks/external.py index cc671ad..62b57f4 100644 --- a/httpdbg/hooks/external.py +++ b/httpdbg/hooks/external.py @@ -7,7 +7,6 @@ import tempfile import time import threading -from typing import List from typing import Union from httpdbg.env import HTTPDBG_MULTIPROCESS_DIR @@ -18,7 +17,7 @@ @contextmanager def watcher_external( records: HTTPRecords, - initiators: Union[List[str], None] = None, + initiators: Union[list[str], None] = None, server: bool = False, ) -> Generator[HTTPRecords, None, None]: if HTTPDBG_MULTIPROCESS_DIR not in os.environ: diff --git a/httpdbg/hooks/fastapi.py b/httpdbg/hooks/fastapi.py index 1c0cf3f..88da39a 100644 --- a/httpdbg/hooks/fastapi.py +++ b/httpdbg/hooks/fastapi.py @@ -3,7 +3,6 @@ from contextlib import contextmanager import functools from functools import wraps -from typing import Dict from typing import Generator from typing import Union @@ -37,7 +36,7 @@ def hook(*args, **kwargs): def set_hook_fastapi_apirouter_add_api_route( records: HTTPRecords, method: Callable, - already_mapped: Union[Dict[Callable, Callable], None] = None, + already_mapped: Union[dict[Callable, Callable], None] = None, ): @wraps(method) @@ -123,7 +122,7 @@ def hook_fastapi(records: HTTPRecords) -> Generator[None, None, None]: try: import fastapi.routing - already_mapped: Dict[Callable, Callable] = {} + already_mapped: dict[Callable, Callable] = {} set_hook_fastapi_apirouter_add_api_route_with_already_mapped = ( functools.partial( diff --git a/httpdbg/hooks/flask.py b/httpdbg/hooks/flask.py index 81db61e..9a23930 100644 --- a/httpdbg/hooks/flask.py +++ b/httpdbg/hooks/flask.py @@ -3,7 +3,6 @@ from contextlib import contextmanager import functools from functools import wraps -from typing import Dict from typing import Generator from typing import Union @@ -36,7 +35,7 @@ def hook(*args, **kwargs): def set_hook_flask_add_url_rule( records: HTTPRecords, method: Callable, - already_mapped: Union[Dict[Callable, Callable], None] = None, + already_mapped: Union[dict[Callable, Callable], None] = None, ): def hook(*args, **kwargs): @@ -67,7 +66,7 @@ def hook(*args, **kwargs): def set_hook_flask_register_error_handler( records: HTTPRecords, method: Callable, - already_mapped: Union[Dict[Callable, Callable], None] = None, + already_mapped: Union[dict[Callable, Callable], None] = None, ): def hook(*args, **kwargs): @@ -103,7 +102,7 @@ def hook_flask(records: HTTPRecords) -> Generator[None, None, None]: # we must not apply the hook more than once on a mapped endpoint function # AssertionError: View function mapping is overwriting an existing endpoint function: xxxx - already_mapped: Dict[Callable, Callable] = {} + already_mapped: dict[Callable, Callable] = {} set_hook_flask_add_url_rule_with_already_mapped = functools.partial( set_hook_flask_add_url_rule, already_mapped=already_mapped diff --git a/httpdbg/hooks/generic.py b/httpdbg/hooks/generic.py index bc74b3b..3dbda6f 100644 --- a/httpdbg/hooks/generic.py +++ b/httpdbg/hooks/generic.py @@ -9,7 +9,6 @@ from types import ModuleType from typing import Any from typing import Generator -from typing import List from typing import Union from httpdbg.hooks.utils import decorate @@ -49,13 +48,13 @@ def hook(*args, **kwargs): @contextmanager def hook_generic( - records: HTTPRecords, initiators: Union[List[str], None] = None + records: HTTPRecords, initiators: Union[list[str], None] = None ) -> Generator[None, None, None]: if initiators: # we add a hook for a generic initiator only if the module is imported - hooks: List[Callable] = [] - already_hooked: List[str] = [] + hooks: list[Callable] = [] + already_hooked: list[str] = [] original_builtin_import = builtins.__import__ @@ -130,7 +129,7 @@ def __hook__import__( fnc = undecorate(fnc) -def list_callables_from_module(records: HTTPRecords, module: str) -> List[Any]: +def list_callables_from_module(records: HTTPRecords, module: str) -> list[Any]: callables = [] try: @@ -180,7 +179,7 @@ def list_callables_from_class( imported_module: ModuleType, module: str, classname: str, -) -> List[Any]: +) -> list[Any]: callables = [] try: diff --git a/httpdbg/hooks/h2.py b/httpdbg/hooks/h2.py new file mode 100644 index 0000000..d6da37f --- /dev/null +++ b/httpdbg/hooks/h2.py @@ -0,0 +1,117 @@ +# -*- coding: utf-8 -*- +from collections.abc import Callable +from contextlib import contextmanager +import traceback +from typing import Generator + +from httpdbg.hooks.utils import getcallargs +from httpdbg.hooks.utils import decorate +from httpdbg.hooks.utils import undecorate +from httpdbg.initiator import httpdbg_initiator +from httpdbg.records import HTTPRecords + + +def set_hook_for_h2_send_headers(records: HTTPRecords, method: Callable): + def hook(*args, **kwargs): + callargs = getcallargs(method, *args, **kwargs) + print(callargs) + initiator_and_group = None + try: + with httpdbg_initiator( + records, traceback.extract_stack(), method, *args, **kwargs + ) as initiator_and_group: + ret = method(*args, **kwargs) + return ret + except Exception as ex: + raise + # callargs = getcallargs(method, *args, **kwargs) + + # if "url" in callargs: + # if initiator_and_group: + # initiator, group, is_new = initiator_and_group + # if is_new: + # records.add_new_record_exception( + # initiator, group, str(callargs["url"]), ex + # ) + # raise + + return hook + + +def set_hook_for_h2_send_data(records: HTTPRecords, method: Callable): + def hook(*args, **kwargs): + callargs = getcallargs(method, *args, **kwargs) + print(callargs) + initiator_and_group = None + try: + with httpdbg_initiator( + records, traceback.extract_stack(), method, *args, **kwargs + ) as initiator_and_group: + ret = method(*args, **kwargs) + return ret + except Exception as ex: + raise + # callargs = getcallargs(method, *args, **kwargs) + + # if "url" in callargs: + # if initiator_and_group: + # initiator, group, is_new = initiator_and_group + # if is_new: + # records.add_new_record_exception( + # initiator, group, str(callargs["url"]), ex + # ) + # raise + + return hook + + +def set_hook_for_h2_receive_data(records: HTTPRecords, method: Callable): + def hook(*args, **kwargs): + # callargs = getcallargs(method, *args, **kwargs) + # print(callargs) + initiator_and_group = None + try: + with httpdbg_initiator( + records, traceback.extract_stack(), method, *args, **kwargs + ) as initiator_and_group: + ret = method(*args, **kwargs) + for event in ret: + print(type(event)) + print(event) + return ret + except Exception as ex: + raise + # callargs = getcallargs(method, *args, **kwargs) + + # if "url" in callargs: + # if initiator_and_group: + # initiator, group, is_new = initiator_and_group + # if is_new: + # records.add_new_record_exception( + # initiator, group, str(callargs["url"]), ex + # ) + # raise + + return hook + + +@contextmanager +def hook_h2(records: HTTPRecords) -> Generator[None, None, None]: + hooks = False + try: + import h2.connection + + h2.connection.H2Connection.send_headers = decorate(records, h2.connection.H2Connection.send_headers, set_hook_for_h2_send_headers) # type: ignore[arg-type] + h2.connection.H2Connection.send_data = decorate(records, h2.connection.H2Connection.send_data, set_hook_for_h2_send_data) # type: ignore[arg-type] + h2.connection.H2Connection.receive_data = decorate(records, h2.connection.H2Connection.receive_data, set_hook_for_h2_receive_data) # type: ignore[arg-type] + + hooks = True + except ImportError: + pass + + yield + + if hooks: + h2.connection.H2Connection.send_headers = undecorate(h2.connection.H2Connection.send_headers) # type: ignore[arg-type] + h2.connection.H2Connection.send_data = undecorate(h2.connection.H2Connection.send_data) # type: ignore[arg-type] + h2.connection.H2Connection.receive_data = undecorate(h2.connection.H2Connection.receive_data) # type: ignore[arg-type] diff --git a/httpdbg/hooks/record.py b/httpdbg/hooks/record.py index b8e2961..0430515 100644 --- a/httpdbg/hooks/record.py +++ b/httpdbg/hooks/record.py @@ -1,8 +1,6 @@ # -*- coding: utf-8 -*- from abc import ABC, abstractmethod import datetime -from typing import List -from typing import Tuple from typing import Union from httpdbg.utils import get_new_uuid @@ -23,7 +21,7 @@ def rawheaders(self) -> bytes: @property @abstractmethod - def headers(self) -> List[HTTPDBGHeader]: + def headers(self) -> list[HTTPDBGHeader]: pass @property @@ -51,7 +49,7 @@ class HTTPRecordRequest(HTTPRecordReqResp, ABC): @property @abstractmethod - def cookies(self) -> List[HTTPDBGCookie]: + def cookies(self) -> list[HTTPDBGCookie]: pass @property @@ -74,7 +72,7 @@ class HTTPRecordResponse(HTTPRecordReqResp, ABC): @property @abstractmethod - def cookies(self) -> List[HTTPDBGCookie]: + def cookies(self) -> list[HTTPDBGCookie]: pass @property @@ -107,7 +105,7 @@ def __init__( is_client: bool = True, ) -> None: self.id = get_new_uuid() - self.address: Tuple[str, int] = ("", 0) + self.address: tuple[str, int] = ("", 0) self._url: Union[str, None] = None self.initiator_id: Union[str, None] = initiator_id self.exception: Union[Exception, None] = None diff --git a/httpdbg/hooks/recordhttp1.py b/httpdbg/hooks/recordhttp1.py index 2835333..c4d795d 100644 --- a/httpdbg/hooks/recordhttp1.py +++ b/httpdbg/hooks/recordhttp1.py @@ -1,6 +1,5 @@ import datetime from urllib.parse import urlparse -from typing import List from httpdbg.preview import generate_preview from httpdbg.hooks.record import HTTPRecord @@ -18,7 +17,7 @@ class HTTP1RecordReqResp(HTTPRecordReqResp): def __init__(self) -> None: self._rawdata: bytes = bytes() self._rawheaders: bytes = bytes() - self._headers: List[HTTPDBGHeader] = [] + self._headers: list[HTTPDBGHeader] = [] self.last_update: datetime.datetime = datetime.datetime.now( datetime.timezone.utc ) @@ -38,7 +37,7 @@ def rawheaders(self) -> bytes: return self._rawheaders @property - def headers(self) -> List[HTTPDBGHeader]: + def headers(self) -> list[HTTPDBGHeader]: if not self._headers: if self.rawheaders: for header in self.rawheaders[self.rawheaders.find(b"\r\n") :].split( @@ -98,7 +97,7 @@ def __init__(self) -> None: self._protocol = bytes() @property - def cookies(self) -> List[HTTPDBGCookie]: + def cookies(self) -> list[HTTPDBGCookie]: return list_cookies_headers_request_simple_cookies(self.headers) def _parse_first_line(self) -> None: @@ -133,7 +132,7 @@ def __init__(self): self._message = bytes() @property - def cookies(self) -> List[HTTPDBGCookie]: + def cookies(self) -> list[HTTPDBGCookie]: return list_cookies_headers_response_simple_cookies(self.headers) def _parse_first_line(self) -> None: diff --git a/httpdbg/hooks/socket.py b/httpdbg/hooks/socket.py index f67a85d..3e817d4 100644 --- a/httpdbg/hooks/socket.py +++ b/httpdbg/hooks/socket.py @@ -10,7 +10,7 @@ import sys import traceback from typing import Generator -from typing import Dict, Tuple, Union +from typing import Union from httpdbg.initiator import httpdbg_initiator from httpdbg.log import logger @@ -25,9 +25,9 @@ class SocketRawData(object): """Store the request data without encryption, even when using an SSLSocket.""" - def __init__(self, id: int, address: Tuple[str, int], ssl: bool) -> None: + def __init__(self, id: int, address: tuple[str, int], ssl: bool) -> None: self.id: int = id - self.address: Tuple[str, int] = address + self.address: tuple[str, int] = address self.ssl: bool = ssl self._rawdata: bytes = bytes() self.record: Union[HTTP1Record, None] = None @@ -66,10 +66,10 @@ class TracerHTTP1: def __init__( self, - ignore: Tuple[Tuple[str, int], ...] = (), + ignore: tuple[tuple[str, int], ...] = (), ): - self.sockets: Dict[int, SocketRawData] = {} - self.ignore: Tuple[Tuple[str, int], ...] = ignore + self.sockets: dict[int, SocketRawData] = {} + self.ignore: tuple[tuple[str, int], ...] = ignore def get_socket_data( self, obj, extra_sock=None, force_new=False, request=None, is_uvicorn=False diff --git a/httpdbg/initiator.py b/httpdbg/initiator.py index aa8eaa8..3074bd3 100644 --- a/httpdbg/initiator.py +++ b/httpdbg/initiator.py @@ -7,8 +7,6 @@ import platform import traceback from typing import Generator -from typing import List -from typing import Tuple from typing import Union from typing import TYPE_CHECKING @@ -25,7 +23,7 @@ def __init__( self, label: str, short_stack: str, - stack: List[str], + stack: list[str], ): self.id = get_new_uuid() self.label = label @@ -86,7 +84,7 @@ def compatible_path(path: str) -> str: return p -def in_lib(line: str, packages: List[str] = None): +def in_lib(line: str, packages: list[str] = None): if not packages: packages = ["requests", "httpx", "aiohttp", "urllib3"] return any( @@ -99,7 +97,7 @@ def in_lib(line: str, packages: List[str] = None): def get_current_instruction( extracted_stack: traceback.StackSummary, -) -> Tuple[str, str, List[str]]: +) -> tuple[str, str, list[str]]: instruction = "" short_stack = "" stack = [] @@ -161,7 +159,7 @@ def extract_short_stack_from_file( before: int, after: int, stop_if_instruction_ends: bool = True, -) -> Tuple[str, str]: +) -> tuple[str, str]: instruction = "" short_stack = "" @@ -243,7 +241,7 @@ def httpdbg_initiator( original_method: Callable, *args, **kwargs, -) -> Generator[Union[Tuple[Initiator, Group, bool], None], None, None]: +) -> Generator[Union[tuple[Initiator, Group, bool], None], None, None]: try: if records.current_initiator is None: diff --git a/httpdbg/mode_console.py b/httpdbg/mode_console.py index 782aca4..e68af14 100644 --- a/httpdbg/mode_console.py +++ b/httpdbg/mode_console.py @@ -1,6 +1,5 @@ # -*- coding: utf-8 -*- import code -from typing import List from typing import Union from httpdbg.records import HTTPRecords @@ -15,7 +14,7 @@ class InteractiveConsoleWithHistory(code.InteractiveConsole): def __init__(self, records: HTTPRecords, locals=None): self.records: HTTPRecords = records - self.history: List[str] = [] + self.history: list[str] = [] self.incomplete_block: bool = False super().__init__(locals) diff --git a/httpdbg/mode_module.py b/httpdbg/mode_module.py index fe21997..2cb40d7 100644 --- a/httpdbg/mode_module.py +++ b/httpdbg/mode_module.py @@ -2,10 +2,9 @@ import runpy from unittest.mock import patch import sys -from typing import List -def run_module(argv: List[str]) -> None: +def run_module(argv: list[str]) -> None: try: with patch.object(sys, "argv", argv): runpy.run_module(argv[0], run_name="__main__") diff --git a/httpdbg/mode_script.py b/httpdbg/mode_script.py index a855703..bca154f 100644 --- a/httpdbg/mode_script.py +++ b/httpdbg/mode_script.py @@ -3,12 +3,11 @@ import runpy import sys import traceback -from typing import List from httpdbg.log import logger -def run_script(argv: List[str]) -> None: +def run_script(argv: list[str]) -> None: if len(argv) == 0: exit("script mode - error - python file required, but none set") diff --git a/httpdbg/preview.py b/httpdbg/preview.py index 5d7c2ef..cdf926a 100644 --- a/httpdbg/preview.py +++ b/httpdbg/preview.py @@ -1,8 +1,8 @@ # -*- coding: utf-8 -*- -from typing import Tuple, Dict, Union +from typing import Union -def parse_content_type(content_type: str) -> Tuple[str, Dict[str, str]]: +def parse_content_type(content_type: str) -> tuple[str, dict[str, str]]: s = content_type.split(";") media_type = s[0] directives = {} @@ -15,8 +15,8 @@ def parse_content_type(content_type: str) -> Tuple[str, Dict[str, str]]: def generate_preview( raw_data: bytes, content_type: str, content_encoding: str -) -> Dict[str, Union[str, bool]]: - body: Dict[str, Union[str, bool]] = {} +) -> dict[str, Union[str, bool]]: + body: dict[str, Union[str, bool]] = {} body["content_type"] = content_type diff --git a/httpdbg/records.py b/httpdbg/records.py index a466aad..912eac9 100644 --- a/httpdbg/records.py +++ b/httpdbg/records.py @@ -1,7 +1,5 @@ import datetime import sys -from typing import Dict -from typing import Tuple from typing import Union from httpdbg.hooks.record import HTTPRecord @@ -24,11 +22,11 @@ def __init__( self, client: bool = True, server: bool = False, - ignore: Tuple[Tuple[str, int], ...] = (), + ignore: tuple[tuple[str, int], ...] = (), ) -> None: self.client: bool = client self.server: bool = server - self._ignore: Tuple[Tuple[str, int], ...] = ignore + self._ignore: tuple[tuple[str, int], ...] = ignore self.reset() def reset(self) -> None: @@ -36,11 +34,11 @@ def reset(self) -> None: logger().info("HTTPRecords.reset") self.session: HTTPRecordsSessionInfo = HTTPRecordsSessionInfo() - self.requests: Dict[str, HTTPRecord] = {} + self.requests: dict[str, HTTPRecord] = {} self.requests_already_loaded = 0 - self.initiators: Dict[str, Initiator] = {} + self.initiators: dict[str, Initiator] = {} self.current_initiator: Union[str, None] = None - self.groups: Dict[str, Group] = {} + self.groups: dict[str, Group] = {} self.current_group: Union[str, None] = None self.current_tag: Union[str, None] = None self._tracerhttp1: TracerHTTP1 = TracerHTTP1(ignore=self.ignore) @@ -79,7 +77,7 @@ def add_group(self, group: Group): self.current_group = group.id @property - def ignore(self) -> Tuple[Tuple[str, int], ...]: + def ignore(self) -> tuple[tuple[str, int], ...]: return self._ignore @ignore.setter diff --git a/httpdbg/utils.py b/httpdbg/utils.py index 1cb4f8e..e1ab431 100644 --- a/httpdbg/utils.py +++ b/httpdbg/utils.py @@ -2,7 +2,6 @@ from http.cookies import SimpleCookie import secrets import string -from typing import List def get_new_uuid() -> str: @@ -76,8 +75,8 @@ def __eq__(self, other) -> bool: def list_cookies_headers_request_simple_cookies( - headers: List[HTTPDBGHeader], -) -> List[HTTPDBGCookie]: + headers: list[HTTPDBGHeader], +) -> list[HTTPDBGCookie]: lst = [] for header in headers: if header.name.lower() == "cookie": @@ -89,8 +88,8 @@ def list_cookies_headers_request_simple_cookies( def list_cookies_headers_response_simple_cookies( - headers: List[HTTPDBGHeader], -) -> List[HTTPDBGCookie]: + headers: list[HTTPDBGHeader], +) -> list[HTTPDBGCookie]: lst = [] for header in headers: if header.name.lower() == "set-cookie": diff --git a/httpdbg/webapp/api.py b/httpdbg/webapp/api.py index 2100d75..b2e0efa 100644 --- a/httpdbg/webapp/api.py +++ b/httpdbg/webapp/api.py @@ -2,7 +2,6 @@ from json import JSONEncoder import traceback from typing import Any -from typing import Dict from typing import Union from httpdbg.records import HTTPRecords @@ -10,8 +9,8 @@ class RequestPayload(JSONEncoder): - def default(self, req: HTTPRecord) -> Dict[str, Any]: - payload: Dict[str, Any] = { + def default(self, req: HTTPRecord) -> dict[str, Any]: + payload: dict[str, Any] = { "id": req.id, "url": req.url, "netloc": req.netloc, @@ -73,7 +72,7 @@ def default(self, records: HTTPRecords): records, HTTPRecords ), "This encoder works only for HTTPRecords object." - payload: Dict[str, Dict[str, Union[str, dict]]] = { + payload: dict[str, dict[str, Union[str, dict]]] = { "session": { "id": records.session.id, "command_line": records.session.command_line, From 6758d462260a5ee92aa263fdc2dbaa295e368aee Mon Sep 17 00:00:00 2001 From: cle-b Date: Sat, 16 Aug 2025 09:45:01 +0200 Subject: [PATCH 2/2] remove file --- httpdbg/hooks/h2.py | 117 -------------------------------------------- 1 file changed, 117 deletions(-) delete mode 100644 httpdbg/hooks/h2.py diff --git a/httpdbg/hooks/h2.py b/httpdbg/hooks/h2.py deleted file mode 100644 index d6da37f..0000000 --- a/httpdbg/hooks/h2.py +++ /dev/null @@ -1,117 +0,0 @@ -# -*- coding: utf-8 -*- -from collections.abc import Callable -from contextlib import contextmanager -import traceback -from typing import Generator - -from httpdbg.hooks.utils import getcallargs -from httpdbg.hooks.utils import decorate -from httpdbg.hooks.utils import undecorate -from httpdbg.initiator import httpdbg_initiator -from httpdbg.records import HTTPRecords - - -def set_hook_for_h2_send_headers(records: HTTPRecords, method: Callable): - def hook(*args, **kwargs): - callargs = getcallargs(method, *args, **kwargs) - print(callargs) - initiator_and_group = None - try: - with httpdbg_initiator( - records, traceback.extract_stack(), method, *args, **kwargs - ) as initiator_and_group: - ret = method(*args, **kwargs) - return ret - except Exception as ex: - raise - # callargs = getcallargs(method, *args, **kwargs) - - # if "url" in callargs: - # if initiator_and_group: - # initiator, group, is_new = initiator_and_group - # if is_new: - # records.add_new_record_exception( - # initiator, group, str(callargs["url"]), ex - # ) - # raise - - return hook - - -def set_hook_for_h2_send_data(records: HTTPRecords, method: Callable): - def hook(*args, **kwargs): - callargs = getcallargs(method, *args, **kwargs) - print(callargs) - initiator_and_group = None - try: - with httpdbg_initiator( - records, traceback.extract_stack(), method, *args, **kwargs - ) as initiator_and_group: - ret = method(*args, **kwargs) - return ret - except Exception as ex: - raise - # callargs = getcallargs(method, *args, **kwargs) - - # if "url" in callargs: - # if initiator_and_group: - # initiator, group, is_new = initiator_and_group - # if is_new: - # records.add_new_record_exception( - # initiator, group, str(callargs["url"]), ex - # ) - # raise - - return hook - - -def set_hook_for_h2_receive_data(records: HTTPRecords, method: Callable): - def hook(*args, **kwargs): - # callargs = getcallargs(method, *args, **kwargs) - # print(callargs) - initiator_and_group = None - try: - with httpdbg_initiator( - records, traceback.extract_stack(), method, *args, **kwargs - ) as initiator_and_group: - ret = method(*args, **kwargs) - for event in ret: - print(type(event)) - print(event) - return ret - except Exception as ex: - raise - # callargs = getcallargs(method, *args, **kwargs) - - # if "url" in callargs: - # if initiator_and_group: - # initiator, group, is_new = initiator_and_group - # if is_new: - # records.add_new_record_exception( - # initiator, group, str(callargs["url"]), ex - # ) - # raise - - return hook - - -@contextmanager -def hook_h2(records: HTTPRecords) -> Generator[None, None, None]: - hooks = False - try: - import h2.connection - - h2.connection.H2Connection.send_headers = decorate(records, h2.connection.H2Connection.send_headers, set_hook_for_h2_send_headers) # type: ignore[arg-type] - h2.connection.H2Connection.send_data = decorate(records, h2.connection.H2Connection.send_data, set_hook_for_h2_send_data) # type: ignore[arg-type] - h2.connection.H2Connection.receive_data = decorate(records, h2.connection.H2Connection.receive_data, set_hook_for_h2_receive_data) # type: ignore[arg-type] - - hooks = True - except ImportError: - pass - - yield - - if hooks: - h2.connection.H2Connection.send_headers = undecorate(h2.connection.H2Connection.send_headers) # type: ignore[arg-type] - h2.connection.H2Connection.send_data = undecorate(h2.connection.H2Connection.send_data) # type: ignore[arg-type] - h2.connection.H2Connection.receive_data = undecorate(h2.connection.H2Connection.receive_data) # type: ignore[arg-type]