Skip to content

Commit 775f58b

Browse files
committed
Handle scope["server"] = None, by defaulting to 0.0.0.0:80
1 parent 9c4242d commit 775f58b

2 files changed

Lines changed: 23 additions & 7 deletions

File tree

ext/opentelemetry-ext-asgi/src/opentelemetry/ext/asgi/__init__.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -79,19 +79,17 @@ def http_status_to_canonical_code(code: int, allow_redirect: bool = True):
7979
def collect_request_attributes(scope):
8080
"""Collects HTTP request attributes from the ASGI scope and returns a
8181
dictionary to be used as span creation attributes."""
82-
83-
port = scope.get("server")[1]
84-
server_host = scope.get("server")[0] + (
85-
":" + str(port) if port != 80 else ""
86-
)
82+
server = scope.get("server") or ['0.0.0.0', 80]
83+
port = server[1]
84+
server_host = server[0] + (":" + str(port) if port != 80 else "")
8785
http_url = scope.get("scheme") + "://" + server_host + scope.get("path")
8886
if scope.get("query_string"):
8987
http_url = http_url + ("?" + scope.get("query_string").decode("utf8"))
9088

9189
result = {
9290
"component": scope.get("type"),
9391
"http.method": scope.get("method"),
94-
"http.server_name": scope.get("server")[0],
92+
"http.server_name": server[0],
9593
"http.scheme": scope.get("scheme"),
9694
"http.host": server_host,
9795
"host.port": port,

ext/opentelemetry-ext-asgi/tests/test_asgi_middleware.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ def validate_outputs(self, outputs, error=None, modifiers=None):
133133
for span, expected in zip(span_list, expected):
134134
self.assertEqual(span.name, expected["name"])
135135
self.assertEqual(span.kind, expected["kind"])
136-
self.assertEqual(span.attributes, expected["attributes"])
136+
self.assertDictEqual(dict(span.attributes), expected["attributes"])
137137

138138
def test_basic_asgi_call(self):
139139
"""Test that spans are emitted as expected."""
@@ -170,6 +170,24 @@ def update_expected_span_name(expected):
170170
outputs = self.get_all_output()
171171
self.validate_outputs(outputs, modifiers=[update_expected_span_name])
172172

173+
def test_behavior_with_scope_server_as_none(self):
174+
"""Test that middleware is ok when server is none in scope."""
175+
def update_expected_server(expected):
176+
expected[3]['attributes'].update({
177+
'http.server_name': '0.0.0.0',
178+
'http.host': '0.0.0.0',
179+
'host.port': 80,
180+
'http.url': 'http://0.0.0.0/'
181+
})
182+
return expected
183+
self.scope["server"] = None
184+
app = otel_asgi.OpenTelemetryMiddleware(simple_asgi)
185+
self.seed_app(app)
186+
self.send_default_request()
187+
outputs = self.get_all_output()
188+
self.validate_outputs(outputs, modifiers=[update_expected_server])
189+
190+
173191

174192
class TestAsgiAttributes(unittest.TestCase):
175193
def setUp(self):

0 commit comments

Comments
 (0)