models.py 10 KB

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