serializers.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. import logging
  2. import re
  3. import uuid
  4. from datetime import datetime
  5. from urllib.parse import parse_qs
  6. from anonymizeip import anonymize_ip
  7. from django.utils.timezone import make_aware
  8. from ipware import get_client_ip
  9. from rest_framework import serializers
  10. from rest_framework.exceptions import ErrorDetail, ValidationError
  11. from apps.environments.models import Environment
  12. from apps.releases.models import Release
  13. from .models import TransactionEvent, TransactionGroup
  14. logger = logging.getLogger(__name__)
  15. class FlexibleDateTimeField(serializers.DateTimeField):
  16. """Supports both DateTime and unix epoch timestamp"""
  17. def to_internal_value(self, value):
  18. try:
  19. return make_aware(datetime.fromtimestamp(float(value)))
  20. except (ValueError, TypeError):
  21. return super().to_internal_value(value)
  22. class ErrorValueDetail(ErrorDetail):
  23. """Extended ErrorDetail with validation value"""
  24. value = None
  25. def __new__(cls, string, code=None, value=None):
  26. self = super().__new__(cls, string, code)
  27. self.value = value
  28. return self
  29. def __repr__(self):
  30. return "ErrorDetail(string=%r, code=%r, value=%r)" % (
  31. str(self),
  32. self.code,
  33. self.value,
  34. )
  35. class BaseSerializer(serializers.Serializer):
  36. def process_user(self, project, data):
  37. """Fetch user data from SDK event and request"""
  38. user = data.get("user", {})
  39. if self.context and self.context.get("request"):
  40. client_ip, is_routable = get_client_ip(self.context["request"])
  41. if user or is_routable:
  42. if is_routable:
  43. if project.should_scrub_ip_addresses:
  44. client_ip = anonymize_ip(client_ip)
  45. user["ip_address"] = client_ip
  46. return user
  47. class ForgivingFieldMixin:
  48. def update_handled_errors_context(self, errors: list):
  49. if errors:
  50. handled_errors = self.context.get("handled_errors", {})
  51. self.context["handled_errors"] = handled_errors | {self.field_name: errors}
  52. class ForgivingHStoreField(ForgivingFieldMixin, serializers.HStoreField):
  53. def run_child_validation(self, data):
  54. result = {}
  55. errors: list = []
  56. for key, value in data.items():
  57. if value is None:
  58. continue
  59. key = str(key)
  60. try:
  61. result[key] = self.child.run_validation(value)
  62. except ValidationError as e:
  63. for detail in e.detail:
  64. errors.append(ErrorValueDetail(str(detail), detail.code, value))
  65. if errors:
  66. self.update_handled_errors_context(errors)
  67. return result
  68. class QueryStringField(serializers.ListField):
  69. """
  70. Can be given as unparsed string, dictionary, or list of tuples
  71. Should store as List[List[str]] where inner List is always of length 2
  72. """
  73. child = serializers.ListField(child=serializers.CharField())
  74. def to_internal_value(self, data):
  75. if isinstance(data, str) and data:
  76. qs = parse_qs(data)
  77. result = []
  78. for key, values in qs.items():
  79. for value in values:
  80. result.append([key, value])
  81. return result
  82. elif isinstance(data, dict):
  83. return [[key, value] for key, value in data.items()]
  84. elif isinstance(data, list):
  85. result = []
  86. for item in data:
  87. if isinstance(item, list) and len(item) >= 2:
  88. result.append(item[:2])
  89. return result
  90. return None
  91. class RequestSerializer(serializers.Serializer):
  92. env = serializers.DictField(
  93. child=serializers.CharField(allow_blank=True, allow_null=True), required=False
  94. )
  95. # Dict values can be both str and List[str]
  96. headers = serializers.DictField(required=False)
  97. url = serializers.CharField(required=False, allow_blank=True)
  98. method = serializers.CharField(required=False, allow_blank=True)
  99. query_string = QueryStringField(required=False, allow_null=True)
  100. class ForgivingDisallowRegexField(ForgivingFieldMixin, serializers.CharField):
  101. """Disallow bad matches, set disallow_regex kwarg to use"""
  102. def __init__(self, **kwargs):
  103. self.disallow_regex = kwargs.pop("disallow_regex", None)
  104. super().__init__(**kwargs)
  105. def to_internal_value(self, data):
  106. data = super().to_internal_value(data)
  107. if self.disallow_regex:
  108. pattern = re.compile(self.disallow_regex)
  109. if pattern.match(data) is None:
  110. error = ErrorValueDetail(
  111. "invalid characters in string", "invalid_data", data
  112. )
  113. self.update_handled_errors_context([error])
  114. return None
  115. return data
  116. class SentrySDKEventSerializer(BaseSerializer):
  117. """Represents events coming from a OSS sentry SDK client"""
  118. breadcrumbs = serializers.JSONField(required=False)
  119. fingerprint = serializers.ListField(child=serializers.CharField(), required=False)
  120. tags = ForgivingHStoreField(required=False)
  121. event_id = serializers.UUIDField(required=False, default=uuid.uuid4)
  122. extra = serializers.JSONField(required=False)
  123. request = RequestSerializer(required=False)
  124. server_name = serializers.CharField(required=False)
  125. sdk = serializers.JSONField(required=False)
  126. platform = serializers.CharField(required=False)
  127. release = serializers.CharField(required=False, allow_null=True, allow_blank=True)
  128. environment = ForgivingDisallowRegexField(
  129. required=False, allow_null=True, disallow_regex=r"^[^\n\r\f\/]*$"
  130. )
  131. _meta = serializers.JSONField(required=False)
  132. def set_environment(self, name: str, project) -> str:
  133. if not project.environment_id and name:
  134. environment, _ = Environment.objects.get_or_create(
  135. name=name[: Environment._meta.get_field("name").max_length],
  136. organization=project.organization,
  137. )
  138. environment.projects.add(project)
  139. project.environment_id = environment.id
  140. return environment.name
  141. return name
  142. def set_release(self, version: str, project) -> str:
  143. """
  144. Set project.release_id if not already so
  145. Create needed Release if necessary
  146. """
  147. if not project.release_id and version:
  148. release, _ = Release.objects.get_or_create(
  149. version=version, organization=project.organization
  150. )
  151. release.projects.add(project)
  152. project.release_id = release.id
  153. return release.version
  154. return version
  155. class TransactionGroupSerializer(serializers.ModelSerializer):
  156. avgDuration = serializers.IntegerField(source="avg_duration", read_only=True)
  157. transactionCount = serializers.IntegerField(
  158. source="transaction_count", read_only=True
  159. )
  160. class Meta:
  161. model = TransactionGroup
  162. fields = [
  163. "id",
  164. "transaction",
  165. "project",
  166. "op",
  167. "method",
  168. "avgDuration",
  169. "transactionCount",
  170. ]
  171. class TransactionEventSerializer(SentrySDKEventSerializer):
  172. type = serializers.CharField(required=False)
  173. contexts = serializers.JSONField()
  174. measurements = serializers.JSONField(required=False)
  175. start_timestamp = FlexibleDateTimeField()
  176. timestamp = FlexibleDateTimeField()
  177. transaction = serializers.CharField()
  178. def create(self, validated_data):
  179. data = validated_data
  180. contexts = data["contexts"]
  181. project = self.context.get("project")
  182. trace_id = contexts["trace"]["trace_id"]
  183. tags = []
  184. release = self.set_release(data.get("release"), project)
  185. if project.release_id:
  186. tags.append(("release", release))
  187. environment = self.set_environment(data.get("environment"), project)
  188. if project.environment_id:
  189. tags.append(("environment", environment))
  190. if data.get("tags"):
  191. tags += [(k, v) for k, v in data["tags"].items()]
  192. defaults = {}
  193. defaults["tags"] = {tag[0]: [tag[1]] for tag in tags}
  194. group, group_created = TransactionGroup.objects.get_or_create(
  195. project=self.context.get("project"),
  196. transaction=data["transaction"],
  197. op=contexts["trace"].get("op", ""),
  198. method=data.get("request", {}).get("method"),
  199. defaults=defaults,
  200. )
  201. # Merge tags, only save if necessary
  202. update_group = False
  203. if not group_created:
  204. for tag in tags:
  205. if tag[0] not in group.tags:
  206. new_tag_value = tag[1]
  207. # Coerce to List[str]
  208. if isinstance(new_tag_value, str):
  209. new_tag_value = [new_tag_value]
  210. group.tags[tag[0]] = new_tag_value
  211. update_group = True
  212. elif tag[1] not in group.tags[tag[0]]:
  213. group.tags[tag[0]].append(tag[1])
  214. update_group = True
  215. if update_group:
  216. group.save(update_fields=["tags"])
  217. transaction = TransactionEvent.objects.create(
  218. group=group,
  219. data={
  220. "request": data.get("request"),
  221. "sdk": data.get("sdk"),
  222. "platform": data.get("platform"),
  223. },
  224. trace_id=trace_id,
  225. event_id=data["event_id"],
  226. timestamp=data["timestamp"],
  227. start_timestamp=data["start_timestamp"],
  228. duration=(data["timestamp"] - data["start_timestamp"]).total_seconds()
  229. * 1000,
  230. tags={tag[0]: tag[1] for tag in tags},
  231. )
  232. return transaction
  233. class TransactionSerializer(serializers.ModelSerializer):
  234. eventId = serializers.UUIDField(source="pk")
  235. startTimestamp = serializers.DateTimeField(source="start_timestamp")
  236. transaction = serializers.SerializerMethodField()
  237. op = serializers.SerializerMethodField()
  238. method = serializers.SerializerMethodField()
  239. class Meta:
  240. model = TransactionEvent
  241. fields = (
  242. "eventId",
  243. "timestamp",
  244. "startTimestamp",
  245. "transaction",
  246. "op",
  247. "method",
  248. )
  249. def get_transaction(self, obj):
  250. return obj.group.transaction
  251. def get_op(self, obj):
  252. return obj.group.op
  253. def get_method(self, obj):
  254. return obj.group.transaction
  255. class TransactionDetailSerializer(TransactionSerializer):
  256. pass