models.py 9.7 KB

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