Skip to content

Commit 8a4362e

Browse files
committed
Upload current snapshot.
1 parent 9906a13 commit 8a4362e

File tree

9 files changed

+137
-103
lines changed

9 files changed

+137
-103
lines changed

opentelemetry-instrumentation/src/opentelemetry/instrumentation/_blobupload/api/blob.py

Lines changed: 34 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1+
import base64
12
from typing import Dict, Optional
23

3-
import base64
44

55
class Blob(object):
66
"""Represents an opaque binary object and associated metadata.
7-
7+
88
This object conteptually has the following properties:
99
1010
- raw_bytes: the actual data (payload) of the Blob
@@ -13,9 +13,14 @@ class Blob(object):
1313
the object such as {"trace_id": "...", "span_id": "...", "filename": ...}
1414
"""
1515

16-
def __init__(self, raw_bytes: bytes, content_type: Optional[str]=None, labels: Optional[Dict[str, str]]=None):
16+
def __init__(
17+
self,
18+
raw_bytes: bytes,
19+
content_type: Optional[str] = None,
20+
labels: Optional[Dict[str, str]] = None,
21+
):
1722
"""Initialize the blob with an explicit set of properties.
18-
23+
1924
Args:
2025
raw_bytes: the required payload
2126
content_type: the MIME type describing the type of data in the payload
@@ -26,31 +31,41 @@ def __init__(self, raw_bytes: bytes, content_type: Optional[str]=None, labels: O
2631
self._labels = labels or {}
2732

2833
@staticmethod
29-
def from_data_uri(cls, uri: str, labels: Optional[dict]=None) -> 'Blob':
34+
def from_data_uri(cls, uri: str, labels: Optional[dict] = None) -> "Blob":
3035
"""Instantiate a blob from a 'data:...' URI.
3136
32-
Args:
37+
Args:
3338
uri: A URI in the 'data:' format. Supports a subset of 'data:' URIs
3439
that encode the data with the 'base64' extension and that include
3540
a content type. Should work with any normal 'image/jpeg', 'image/png',
3641
'application/pdf', 'audio/aac', and many others. DOES NOT SUPPORT
3742
encoding data as percent-encoded text (no "base64").
38-
43+
3944
labels: Additional key/value data to include in the constructed Blob.
4045
"""
41-
if not uri.startswith('data:'):
42-
raise ValueError('Invalid "uri"; expected "data:" prefix. Found: "{}"'.format(uri))
43-
if not ';base64,' in uri:
44-
raise ValueError('Invalid "uri"; expected ";base64," section. Found: "{}"'.format(uri))
45-
data_prefix_len = len('data:')
46+
if not uri.startswith("data:"):
47+
raise ValueError(
48+
'Invalid "uri"; expected "data:" prefix. Found: "{}"'.format(
49+
uri
50+
)
51+
)
52+
if ";base64," not in uri:
53+
raise ValueError(
54+
'Invalid "uri"; expected ";base64," section. Found: "{}"'.format(
55+
uri
56+
)
57+
)
58+
data_prefix_len = len("data:")
4659
after_data_prefix = uri[data_prefix_len:]
47-
if ';' not in after_data_prefix:
48-
raise ValueError('Invalid "uri"; expected ";" in URI. Found: "{}"'.format(uri))
49-
content_type, remaining = after_data_prefix.split(';', 1)
50-
while not remaining.startswith('base64,'):
51-
_, remaining = remaining.split(';', 1)
52-
assert remaining.startswith('base64,')
53-
base64_len = len('base64,')
60+
if ";" not in after_data_prefix:
61+
raise ValueError(
62+
'Invalid "uri"; expected ";" in URI. Found: "{}"'.format(uri)
63+
)
64+
content_type, remaining = after_data_prefix.split(";", 1)
65+
while not remaining.startswith("base64,"):
66+
_, remaining = remaining.split(";", 1)
67+
assert remaining.startswith("base64,")
68+
base64_len = len("base64,")
5469
base64_encoded_content = remaining[base64_len:]
5570
try:
5671
raw_bytes = base64.standard_b64decode(base64_encoded_content)

opentelemetry-instrumentation/src/opentelemetry/instrumentation/_blobupload/api/blob_uploader.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,15 @@
22

33
import abc
44

5-
from opentelemetry.instrumentation._blobupload.api.constants import NOT_UPLOADED
65
from opentelemetry.instrumentation._blobupload.api.blob import Blob
6+
from opentelemetry.instrumentation._blobupload.api.constants import (
7+
NOT_UPLOADED,
8+
)
79

810

911
class BlobUploader(abc.ABC):
1012
"""Pure abstract base class representing a component that does blob uploading."""
11-
13+
1214
@abc.abstractmethod
1315
def upload_async(self, blob: Blob) -> str:
1416
return NOT_UPLOADED

opentelemetry-instrumentation/src/opentelemetry/instrumentation/_blobupload/api/content_type.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,21 @@
11
"""Provides utilities for automatic content-type detection."""
22

3+
34
# Helper used to handle the possibility of optional 'magic' dependency
45
# being unavailable for guessing the MIME type of raw bytes.
56
class _FallBackModule(object):
67
"""Class that is shaped like the portion of 'magic' we need."""
78

89
def from_buffer(self, raw_bytes, mime=True):
910
"""Fallback, subpar implementation of 'from_buffer'."""
10-
return 'application/octet-stream'
11+
return "application/octet-stream"
1112

1213

1314
# Set up '_module' to either use 'magic' or the fallback.
1415
_module = _FallBackModule()
1516
try:
1617
import magic
18+
1719
_module = magic
1820
except ImportError:
1921
pass
Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,34 @@
11
"""Provides utilities for providing basic identifying labels for blobs."""
22

3+
34
def generate_labels_for_span(trace_id: str, span_id: str) -> dict:
45
"""Returns metadata for a span."""
5-
return {
6-
'otel_type': 'span',
7-
'trace_id': trace_id,
8-
'span_id': span_id
9-
}
6+
return {"otel_type": "span", "trace_id": trace_id, "span_id": span_id}
107

118

12-
def generate_labels_for_event(trace_id: str, span_id: str, event_name: str) -> dict:
9+
def generate_labels_for_event(
10+
trace_id: str, span_id: str, event_name: str
11+
) -> dict:
1312
"""Returns metadata for an event."""
1413
result = generate_labels_for_span(trace_id, span_id)
15-
result.update({
16-
'otel_type': 'event',
17-
'event_name': event_name,
18-
})
14+
result.update(
15+
{
16+
"otel_type": "event",
17+
"event_name": event_name,
18+
}
19+
)
1920
return result
2021

2122

22-
def generate_labels_for_span_event(trace_id: str, span_id: str, event_name: str, event_index: int) -> dict:
23+
def generate_labels_for_span_event(
24+
trace_id: str, span_id: str, event_name: str, event_index: int
25+
) -> dict:
2326
"""Returns metadata for a span event."""
2427
result = generate_labels_for_event(trace_id, span_id, event_name)
25-
result.update({
26-
'otel_type': 'span_event',
27-
'event_index': event_index,
28-
})
28+
result.update(
29+
{
30+
"otel_type": "span_event",
31+
"event_index": event_index,
32+
}
33+
)
2934
return result

opentelemetry-instrumentation/src/opentelemetry/instrumentation/_blobupload/api/provider.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
from typing import Optional
2-
31
import abc
42
import logging
3+
from typing import Optional
54

65
from opentelemetry.instrumentation._blobupload.api.blob import Blob
7-
from opentelemetry.instrumentation._blobupload.api.blob_uploader import BlobUploader
8-
6+
from opentelemetry.instrumentation._blobupload.api.blob_uploader import (
7+
BlobUploader,
8+
)
99

1010
_logger = logging.getLogger(__name__)
1111

@@ -22,7 +22,7 @@ class BlobUploaderProvider(abc.ABC):
2222

2323
def get_blob_uploader(self, use_case: Optional[str]) -> BlobUploader:
2424
"""Returns a BlobUploader for the specified use case.
25-
25+
2626
Args:
2727
use_case: An optional use case that describes what the uploader is for. This could
2828
name a particular package, class, or instrumentation. It is intended to allow
@@ -38,10 +38,14 @@ class _DefaultBlobUploaderProvider(BlobUploaderProvider):
3838
"""Default provider used when none has been configured."""
3939

4040
def get_blob_uploader(self, use_case: Optional[str]) -> BlobUploader:
41-
use_case_formatted = '(None)'
41+
use_case_formatted = "(None)"
4242
if use_case:
4343
use_case_formatted = use_case
44-
_logger.warning('No BlobUploaderProvider configured; returning a no-op for use case {}'.format(use_case_formatted))
44+
_logger.warning(
45+
"No BlobUploaderProvider configured; returning a no-op for use case {}".format(
46+
use_case_formatted
47+
)
48+
)
4549
return _NoOpBlobUploader()
4650

4751

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,21 @@
11
#! /usr/bin/env python3
22

3-
if __name__ == '__main__':
3+
if __name__ == "__main__":
44
import sys
5-
sys.path.append('../../../src')
65

7-
from opentelemetry.instrumentation._blobupload.api import detect_content_type
8-
from PIL import Image
6+
sys.path.append("../../../src")
97

108
import io
119
import unittest
1210

11+
from PIL import Image
12+
13+
from opentelemetry.instrumentation._blobupload.api import detect_content_type
14+
1315

1416
def create_test_image(format):
1517
"""Helper for creating a PIL Image for verifying image format support."""
16-
test_img = Image.new('RGB', (2, 2))
18+
test_img = Image.new("RGB", (2, 2))
1719
output_buffer = io.BytesIO()
1820
test_img.save(output_buffer, format)
1921
result = output_buffer.getvalue()
@@ -23,31 +25,30 @@ def create_test_image(format):
2325

2426

2527
class TestContentType(unittest.TestCase):
26-
2728
def test_detects_plaintext(self):
28-
input = 'this is just regular text'
29+
input = "this is just regular text"
2930
output = detect_content_type(input.encode())
30-
self.assertEqual(output, 'text/plain')
31+
self.assertEqual(output, "text/plain")
3132

3233
def test_detects_json(self):
33-
input = '''{
34+
input = """{
3435
"this": {
3536
"contains": "json"
3637
}
37-
}'''
38+
}"""
3839
output = detect_content_type(input.encode())
39-
self.assertEqual(output, 'application/json')
40+
self.assertEqual(output, "application/json")
4041

4142
def test_detects_jpeg(self):
42-
input = create_test_image('jpeg')
43+
input = create_test_image("jpeg")
4344
output = detect_content_type(input)
44-
self.assertEqual(output, 'image/jpeg')
45+
self.assertEqual(output, "image/jpeg")
4546

4647
def test_detects_png(self):
47-
input = create_test_image('png')
48+
input = create_test_image("png")
4849
output = detect_content_type(input)
49-
self.assertEqual(output, 'image/png')
50+
self.assertEqual(output, "image/png")
5051

5152

52-
if __name__ == '__main__':
53-
unittest.main()
53+
if __name__ == "__main__":
54+
unittest.main()

0 commit comments

Comments
 (0)