Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

tornado: Make requests_client a singleton, not a global.

Alex Vandivere87aecf61cd2
diff --git a/zerver/tornado/django_api.py b/zerver/tornado/django_api.py
index b6d7f0721c9..1e563797d17 100644
--- a/zerver/tornado/django_api.py
+++ b/zerver/tornado/django_api.py
@@ -1,4 +1,5 @@
import logging
+from functools import lru_cache
from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, Union
import requests
@@ -10,12 +11,16 @@ from zerver.models import Client, Realm, UserProfile
from zerver.tornado.event_queue import process_notification
from zerver.tornado.sharding import get_tornado_port, get_tornado_uri, notify_tornado_queue_name
-requests_client = requests.Session()
-for host in ['127.0.0.1', 'localhost']:
- if settings.TORNADO_SERVER and host in settings.TORNADO_SERVER:
- # This seems like the only working solution to ignore proxy in
- # requests library.
- requests_client.trust_env = False
+
+@lru_cache(None)
+def requests_client() -> requests.Session:
+ c = requests.Session()
+ if settings.TORNADO_SERVER:
+ if any(host in settings.TORNADO_SERVER for host in ['127.0.0.1', 'localhost']):
+ # Disable trusting the environment, so requests don't
+ # go through any env-configured external proxy.
+ c.trust_env = False
+ return c
def request_event_queue(user_profile: UserProfile, user_client: Client, apply_markdown: bool,
client_gravatar: bool, slim_presence: bool, queue_lifespan_secs: int,
@@ -45,8 +50,8 @@ def request_event_queue(user_profile: UserProfile, user_client: Client, apply_ma
req['event_types'] = ujson.dumps(event_types)
try:
- resp = requests_client.post(tornado_uri + '/api/v1/events/internal',
- data=req)
+ resp = requests_client().post(tornado_uri + '/api/v1/events/internal',
+ data=req)
except requests.adapters.ConnectionError:
logging.error('Tornado server does not seem to be running, check %s '
'and %s for more information.',
@@ -71,8 +76,8 @@ def get_user_events(user_profile: UserProfile, queue_id: str, last_event_id: int
'secret': settings.SHARED_SECRET,
'client': 'internal',
}
- resp = requests_client.post(tornado_uri + '/api/v1/events/internal',
- data=post_data)
+ resp = requests_client().post(tornado_uri + '/api/v1/events/internal',
+ data=post_data)
resp.raise_for_status()
return resp.json()['events']
@@ -82,9 +87,10 @@ def send_notification_http(realm: Realm, data: Mapping[str, Any]) -> None:
process_notification(data)
else:
tornado_uri = get_tornado_uri(realm)
- requests_client.post(tornado_uri + '/notify_tornado', data=dict(
- data = ujson.dumps(data),
- secret = settings.SHARED_SECRET))
+ requests_client().post(
+ tornado_uri + "/notify_tornado",
+ data=dict(data=ujson.dumps(data), secret=settings.SHARED_SECRET),
+ )
def send_event(realm: Realm, event: Mapping[str, Any],
users: Union[Iterable[int], Iterable[Mapping[str, Any]]]) -> None: