models.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. from datetime import timedelta
  2. from urllib.parse import urlparse
  3. from uuid import uuid4
  4. from django.conf import settings
  5. from django.db import models
  6. from django.db.models import Count, Q
  7. from django.utils.text import slugify
  8. from django_extensions.db.fields import AutoSlugField
  9. from glitchtip.base_models import CreatedModel
  10. class Project(CreatedModel):
  11. """
  12. Projects are permission based namespaces which generally
  13. are the top level entry point for all data.
  14. """
  15. slug = AutoSlugField(populate_from=["name", "organization_id"], max_length=50)
  16. name = models.CharField(max_length=64)
  17. organization = models.ForeignKey(
  18. "organizations_ext.Organization",
  19. on_delete=models.CASCADE,
  20. related_name="projects",
  21. )
  22. platform = models.CharField(max_length=64, blank=True, null=True)
  23. first_event = models.DateTimeField(null=True)
  24. scrub_ip_addresses = models.BooleanField(
  25. default=True,
  26. help_text="Should project anonymize IP Addresses",
  27. )
  28. class Meta:
  29. unique_together = (("organization", "slug"),)
  30. def __str__(self):
  31. return self.name
  32. def save(self, *args, **kwargs):
  33. first = False
  34. if not self.pk:
  35. first = True
  36. super().save(*args, **kwargs)
  37. if first:
  38. ProjectKey.objects.create(project=self)
  39. @property
  40. def should_scrub_ip_addresses(self):
  41. """Organization overrides project setting"""
  42. return self.scrub_ip_addresses or self.organization.scrub_ip_addresses
  43. def slugify_function(self, content):
  44. """
  45. Make the slug the project name. Validate uniqueness with both name and org id.
  46. This works because when it runs on organization_id it returns an empty string.
  47. """
  48. if isinstance(content, str):
  49. return slugify(self.name)
  50. return ""
  51. class ProjectCounter(models.Model):
  52. """
  53. Counter for issue short IDs
  54. - Unique per project
  55. - Autoincrements on each new issue
  56. - Separate table for performance
  57. """
  58. project = models.OneToOneField(Project, on_delete=models.CASCADE)
  59. value = models.PositiveIntegerField()
  60. class ProjectKey(CreatedModel):
  61. """Authentication key for a Project"""
  62. project = models.ForeignKey(Project, on_delete=models.CASCADE)
  63. label = models.CharField(max_length=64, blank=True)
  64. public_key = models.UUIDField(default=uuid4, unique=True, editable=False)
  65. rate_limit_count = models.PositiveSmallIntegerField(blank=True, null=True)
  66. rate_limit_window = models.PositiveSmallIntegerField(blank=True, null=True)
  67. data = models.JSONField(blank=True, null=True)
  68. def __str__(self):
  69. return str(self.public_key)
  70. @classmethod
  71. def from_dsn(cls, dsn: str):
  72. urlparts = urlparse(dsn)
  73. public_key = urlparts.username
  74. project_id = urlparts.path.rsplit("/", 1)[-1]
  75. try:
  76. return ProjectKey.objects.get(public_key=public_key, project=project_id)
  77. except ValueError as err:
  78. # ValueError would come from a non-integer project_id,
  79. # which is obviously a DoesNotExist. We catch and rethrow this
  80. # so anything downstream expecting DoesNotExist works fine
  81. raise ProjectKey.DoesNotExist(
  82. "ProjectKey matching query does not exist."
  83. ) from err
  84. @property
  85. def public_key_hex(self):
  86. """The public key without dashes"""
  87. return self.public_key.hex
  88. def dsn(self):
  89. return self.get_dsn()
  90. def get_dsn(self):
  91. urlparts = settings.GLITCHTIP_URL
  92. # If we do not have a scheme or domain/hostname, dsn is never valid
  93. if not urlparts.netloc or not urlparts.scheme:
  94. return ""
  95. return "%s://%s@%s/%s" % (
  96. urlparts.scheme,
  97. self.public_key_hex,
  98. urlparts.netloc + urlparts.path,
  99. self.project_id,
  100. )
  101. def get_dsn_security(self):
  102. urlparts = settings.GLITCHTIP_URL
  103. if not urlparts.netloc or not urlparts.scheme:
  104. return ""
  105. return "%s://%s/api/%s/security/?glitchtip_key=%s" % (
  106. urlparts.scheme,
  107. urlparts.netloc + urlparts.path,
  108. self.project_id,
  109. self.public_key_hex,
  110. )
  111. class ProjectStatisticBase(models.Model):
  112. project = models.ForeignKey("projects.Project", on_delete=models.CASCADE)
  113. date = models.DateTimeField()
  114. count = models.PositiveIntegerField()
  115. class Meta:
  116. unique_together = (("project", "date"),)
  117. abstract = True
  118. @classmethod
  119. def update(cls, project_id: int, start_time: "datetime"):
  120. """
  121. Update current hour and last hour statistics
  122. start_time should be the time of the last known event creation
  123. This method recalculates both stats, replacing any previous entry
  124. """
  125. current_hour = start_time.replace(second=0, microsecond=0, minute=0)
  126. next_hour = current_hour + timedelta(hours=1)
  127. previous_hour = current_hour - timedelta(hours=1)
  128. projects = Project.objects.filter(pk=project_id)
  129. event_counts = cls.aggregate_queryset(
  130. projects, previous_hour, current_hour, next_hour
  131. )
  132. statistics = []
  133. if event_counts["previous_hour_count"]:
  134. statistics.append(
  135. cls(
  136. project_id=project_id,
  137. date=previous_hour,
  138. count=event_counts["previous_hour_count"],
  139. )
  140. )
  141. if event_counts["current_hour_count"]:
  142. statistics.append(
  143. cls(
  144. project_id=project_id,
  145. date=current_hour,
  146. count=event_counts["current_hour_count"],
  147. )
  148. )
  149. if statistics:
  150. cls.objects.bulk_create(
  151. statistics,
  152. update_conflicts=True,
  153. unique_fields=["project", "date"],
  154. update_fields=["count"],
  155. )
  156. class TransactionEventProjectHourlyStatistic(ProjectStatisticBase):
  157. @classmethod
  158. def aggregate_queryset(
  159. cls,
  160. project_queryset,
  161. previous_hour: "datetime",
  162. current_hour: "datetime",
  163. next_hour: "datetime",
  164. ):
  165. # Redundant filter optimization - otherwise all rows are scanned
  166. return project_queryset.filter(
  167. transactiongroup__transactionevent__created__gte=previous_hour,
  168. transactiongroup__transactionevent__created__lt=next_hour,
  169. ).aggregate(
  170. previous_hour_count=Count(
  171. "transactiongroup__transactionevent",
  172. filter=Q(
  173. transactiongroup__transactionevent__created__gte=previous_hour,
  174. transactiongroup__transactionevent__created__lt=current_hour,
  175. ),
  176. ),
  177. current_hour_count=Count(
  178. "transactiongroup__transactionevent",
  179. filter=Q(
  180. transactiongroup__transactionevent__created__gte=current_hour,
  181. transactiongroup__transactionevent__created__lt=next_hour,
  182. ),
  183. ),
  184. )
  185. class EventProjectHourlyStatistic(ProjectStatisticBase):
  186. @classmethod
  187. def aggregate_queryset(
  188. cls,
  189. project_queryset,
  190. previous_hour: "datetime",
  191. current_hour: "datetime",
  192. next_hour: "datetime",
  193. ):
  194. # Redundant filter optimization - otherwise all rows are scanned
  195. return project_queryset.filter(
  196. issue__event__created__gte=previous_hour,
  197. issue__event__created__lt=next_hour,
  198. ).aggregate(
  199. previous_hour_count=Count(
  200. "issue__event",
  201. filter=Q(
  202. issue__event__created__gte=previous_hour,
  203. issue__event__created__lt=current_hour,
  204. ),
  205. ),
  206. current_hour_count=Count(
  207. "issue__event",
  208. filter=Q(
  209. issue__event__created__gte=current_hour,
  210. issue__event__created__lt=next_hour,
  211. ),
  212. ),
  213. )
  214. class ProjectAlertStatus(models.IntegerChoices):
  215. OFF = 0, "off"
  216. ON = 1, "on"
  217. class UserProjectAlert(models.Model):
  218. """
  219. Determine if user alert notifications should always happen, never, or defer to default
  220. Default is stored as the lack of record.
  221. """
  222. user = models.ForeignKey("users.User", on_delete=models.CASCADE)
  223. project = models.ForeignKey("projects.Project", on_delete=models.CASCADE)
  224. status = models.PositiveSmallIntegerField(choices=ProjectAlertStatus.choices)
  225. class Meta:
  226. unique_together = ("user", "project")