models.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. import random
  2. from urllib.parse import urlparse
  3. from uuid import uuid4
  4. from django.conf import settings
  5. from django.core.validators import MaxValueValidator
  6. from django.db import models
  7. from django.db.models import Count, Q, QuerySet
  8. from django.db.models.functions import Cast
  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=Cast(
  46. Cast( # Postgres can cast int to bool, but not bigint to bool
  47. Count(
  48. "teams__members",
  49. filter=Q(teams__members__user_id=user_id),
  50. distinct=True,
  51. ),
  52. output_field=models.IntegerField(),
  53. ),
  54. output_field=models.BooleanField(),
  55. ),
  56. )
  57. def save(self, *args, **kwargs):
  58. first = False
  59. if not self.pk:
  60. first = True
  61. super().save(*args, **kwargs)
  62. if first:
  63. clear_metrics_cache()
  64. ProjectKey.objects.create(project=self)
  65. def delete(self, *args, **kwargs):
  66. """Mark the record as deleted instead of deleting it"""
  67. # avoid circular import
  68. from apps.projects.tasks import delete_project
  69. super().delete(*args, **kwargs)
  70. delete_project.delay(self.pk)
  71. def force_delete(self, *args, **kwargs):
  72. """Really delete the project and all related data."""
  73. # bulk delete all events
  74. events_qs = IssueEvent.objects.filter(issue__project=self)
  75. events_qs._raw_delete(events_qs.db)
  76. # bulk delete all issues in batches of 1k
  77. issues_qs = self.issues.order_by("id")
  78. while True:
  79. try:
  80. issue_delimiter = issues_qs.values_list("id", flat=True)[
  81. 1000:1001
  82. ].get()
  83. issues_qs.filter(id__lte=issue_delimiter).delete()
  84. except Issue.DoesNotExist:
  85. break
  86. issues_qs.delete()
  87. # lastly delete the project itself
  88. super().force_delete(*args, **kwargs)
  89. clear_metrics_cache()
  90. @property
  91. def should_scrub_ip_addresses(self):
  92. """Organization overrides project setting"""
  93. return self.scrub_ip_addresses or self.organization.scrub_ip_addresses
  94. def slugify_function(self, content):
  95. """
  96. Make the slug the project name. Validate uniqueness with both name and org id.
  97. This works because when it runs on organization_id it returns an empty string.
  98. """
  99. reserved_words = ["new"]
  100. slug = ""
  101. if isinstance(content, str):
  102. slug = slugify(self.name)
  103. if slug in reserved_words:
  104. slug += "-1"
  105. return slug
  106. @property
  107. def is_accepting_events(self):
  108. """Is the project in its limits for event creation"""
  109. if self.event_throttle_rate == 0:
  110. return True
  111. return random.randint(0, 100) > self.event_throttle_rate
  112. class ProjectCounter(models.Model):
  113. """
  114. Counter for issue short IDs
  115. - Unique per project
  116. - Autoincrements on each new issue
  117. - Separate table for performance
  118. """
  119. project = models.OneToOneField(Project, on_delete=models.CASCADE)
  120. value = models.PositiveIntegerField()
  121. class ProjectKey(CreatedModel):
  122. """Authentication key for a Project"""
  123. project = models.ForeignKey(Project, on_delete=models.CASCADE)
  124. is_active = models.BooleanField(default=True)
  125. name = models.CharField(max_length=64, blank=True)
  126. public_key = models.UUIDField(default=uuid4, unique=True, editable=False)
  127. rate_limit_count = models.PositiveSmallIntegerField(blank=True, null=True)
  128. rate_limit_window = models.PositiveSmallIntegerField(blank=True, null=True)
  129. data = models.JSONField(blank=True, null=True)
  130. def __str__(self):
  131. return str(self.public_key)
  132. @classmethod
  133. def from_dsn(cls, dsn: str):
  134. urlparts = urlparse(dsn)
  135. public_key = urlparts.username
  136. project_id = urlparts.path.rsplit("/", 1)[-1]
  137. try:
  138. return ProjectKey.objects.get(public_key=public_key, project=project_id)
  139. except ValueError as err:
  140. # ValueError would come from a non-integer project_id,
  141. # which is obviously a DoesNotExist. We catch and rethrow this
  142. # so anything downstream expecting DoesNotExist works fine
  143. raise ProjectKey.DoesNotExist(
  144. "ProjectKey matching query does not exist."
  145. ) from err
  146. @property
  147. def public_key_hex(self):
  148. """The public key without dashes"""
  149. return self.public_key.hex
  150. def dsn(self):
  151. return self.get_dsn()
  152. def get_dsn(self):
  153. urlparts = settings.GLITCHTIP_URL
  154. # If we do not have a scheme or domain/hostname, dsn is never valid
  155. if not urlparts.netloc or not urlparts.scheme:
  156. return ""
  157. return "%s://%s@%s/%s" % (
  158. urlparts.scheme,
  159. self.public_key_hex,
  160. urlparts.netloc + urlparts.path,
  161. self.project_id,
  162. )
  163. def get_dsn_security(self):
  164. urlparts = settings.GLITCHTIP_URL
  165. if not urlparts.netloc or not urlparts.scheme:
  166. return ""
  167. return "%s://%s/api/%s/security/?glitchtip_key=%s" % (
  168. urlparts.scheme,
  169. urlparts.netloc + urlparts.path,
  170. self.project_id,
  171. self.public_key_hex,
  172. )
  173. class ProjectStatisticBase(AggregationModel):
  174. project = models.ForeignKey("projects.Project", on_delete=models.CASCADE)
  175. class Meta:
  176. unique_together = (("project", "date"),)
  177. abstract = True
  178. class TransactionEventProjectHourlyStatistic(ProjectStatisticBase):
  179. class PartitioningMeta(AggregationModel.PartitioningMeta):
  180. pass
  181. class IssueEventProjectHourlyStatistic(ProjectStatisticBase):
  182. class PartitioningMeta(AggregationModel.PartitioningMeta):
  183. pass
  184. class ProjectAlertStatus(models.IntegerChoices):
  185. OFF = 0, "off"
  186. ON = 1, "on"
  187. class UserProjectAlert(models.Model):
  188. """
  189. Determine if user alert notifications should always happen, never, or defer to default
  190. Default is stored as the lack of record.
  191. """
  192. user = models.ForeignKey("users.User", on_delete=models.CASCADE)
  193. project = models.ForeignKey("projects.Project", on_delete=models.CASCADE)
  194. status = models.PositiveSmallIntegerField(choices=ProjectAlertStatus.choices)
  195. class Meta:
  196. unique_together = ("user", "project")