models.py 10 KB

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