Skip to content

Commit 52b4857

Browse files
feat: reuse session (#125)
1 parent 2915c87 commit 52b4857

File tree

1 file changed

+29
-9
lines changed

1 file changed

+29
-9
lines changed

src/lumigo_tracer/utils.py

Lines changed: 29 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,23 +5,24 @@
55
import os
66
import re
77
import time
8-
import urllib.request
9-
from urllib.error import URLError
8+
import http.client
109
from collections import OrderedDict
1110
from typing import Union, List, Optional, Dict, Any
1211
from contextlib import contextmanager
1312
from base64 import b64encode
1413
import inspect
1514

1615
EXECUTION_TAGS_KEY = "lumigo_execution_tags_no_scrub"
17-
EDGE_HOST = "https://{region}.lumigo-tracer-edge.golumigo.com/api/spans"
16+
EDGE_HOST = "{region}.lumigo-tracer-edge.golumigo.com"
17+
EDGE_PATH = "/api/spans"
1818
LOG_FORMAT = "#LUMIGO# - %(asctime)s - %(levelname)s - %(message)s"
1919
SECONDS_TO_TIMEOUT = 0.5
2020
LUMIGO_EVENT_KEY = "_lumigo"
2121
STEP_FUNCTION_UID_KEY = "step_function_uid"
2222
# number of spans that are too big to enter the reported message before break
2323
TOO_BIG_SPANS_THRESHOLD = 5
2424
MAX_SIZE_FOR_REQUEST: int = int(os.environ.get("LUMIGO_MAX_SIZE_FOR_REQUEST", 900_000))
25+
EDGE_TIMEOUT = float(os.environ.get("LUMIGO_EDGE_TIMEOUT", SECONDS_TO_TIMEOUT))
2526
MAX_VARS_SIZE = 100_000
2627
MAX_VAR_LEN = 200
2728
MAX_ENTRY_SIZE = 2048
@@ -50,6 +51,17 @@
5051

5152
_logger: Union[logging.Logger, None] = None
5253

54+
edge_connection = None
55+
try:
56+
# Try to establish the connection in initialization
57+
if os.environ.get("LUMIGO_INITIALIZATION_CONNECTION", "").lower() != "false":
58+
edge_connection = http.client.HTTPSConnection( # type: ignore
59+
EDGE_HOST.format(region=os.environ.get("AWS_REGION")), timeout=EDGE_TIMEOUT
60+
)
61+
edge_connection.connect()
62+
except Exception:
63+
pass
64+
5365

5466
class Configuration:
5567
should_report: bool = True
@@ -182,24 +194,32 @@ def report_json(region: Union[None, str], msgs: List[dict]) -> int:
182194
:return: The duration of reporting (in milliseconds),
183195
or 0 if we didn't send (due to configuration or fail).
184196
"""
197+
global edge_connection
185198
get_logger().info(f"reporting the messages: {msgs[:10]}")
186199
host = Configuration.host or EDGE_HOST.format(region=region)
187200
duration = 0
201+
if not edge_connection or edge_connection.host != host:
202+
try:
203+
edge_connection = http.client.HTTPSConnection( # type: ignore
204+
host.lstrip("https://").rstrip(EDGE_PATH), timeout=EDGE_TIMEOUT
205+
)
206+
except Exception as e:
207+
get_logger().exception(f"Could not establish connection to {host}", exc_info=e)
208+
return duration
188209
if Configuration.should_report:
189210
try:
190211
prune_trace: bool = not os.environ.get("LUMIGO_PRUNE_TRACE_OFF", "").lower() == "true"
191212
to_send = _create_request_body(msgs, prune_trace).encode()
192213
start_time = time.time()
193-
response = urllib.request.urlopen(
194-
urllib.request.Request(host, to_send, headers={"Content-Type": "application/json"}),
195-
timeout=float(os.environ.get("LUMIGO_EDGE_TIMEOUT", SECONDS_TO_TIMEOUT)),
214+
edge_connection.request(
215+
"POST", EDGE_PATH, to_send, headers={"Content-Type": "application/json"}
196216
)
217+
response = edge_connection.getresponse()
218+
response.read() # We most read the response to keep the connection available
197219
duration = int((time.time() - start_time) * 1000)
198220
get_logger().info(f"successful reporting, code: {getattr(response, 'code', 'unknown')}")
199-
except URLError as e:
200-
get_logger().exception(f"Timeout when reporting to {host}", exc_info=e)
201221
except Exception as e:
202-
get_logger().exception(f"could not report json to {host}", exc_info=e)
222+
get_logger().exception(f"Could not report json to {host}", exc_info=e)
203223
return duration
204224

205225

0 commit comments

Comments
 (0)