utils.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import hashlib
  2. from typing import TYPE_CHECKING, List, Optional, Union
  3. from django.core.cache import cache
  4. from .schema import EventMessage
  5. if TYPE_CHECKING:
  6. from apps.issue_events.models import IssueEventType
  7. def default_hash_input(title: str, culprit: str, type: "IssueEventType") -> str:
  8. return title + culprit + str(type)
  9. def generate_hash(
  10. title: str, culprit: str, type: "IssueEventType", extra: Optional[List[str]] = None
  11. ) -> str:
  12. """Generate insecure hash used for grouping issues"""
  13. if extra:
  14. hash_input = "".join(
  15. [
  16. default_hash_input(title, culprit, type)
  17. if part == "{{ default }}"
  18. else part
  19. for part in extra
  20. ]
  21. )
  22. else:
  23. hash_input = default_hash_input(title, culprit, type)
  24. return hashlib.md5(hash_input.encode()).hexdigest()
  25. def transform_parameterized_message(message: Union[str, EventMessage]) -> str:
  26. """
  27. Accept str or Event Message interface
  28. Returns formatted string with interpolation
  29. Both examples would return "Hello there":
  30. {
  31. "message": "Hello %s",
  32. "params": ["there"]
  33. }
  34. {
  35. "message": "Hello {foo}",
  36. "params": {"foo": "there"}
  37. }
  38. """
  39. if isinstance(message, str):
  40. return message
  41. if not message.formatted and message.message:
  42. params = message.params
  43. if isinstance(params, list) and params:
  44. return message.message % tuple(params)
  45. elif isinstance(params, dict):
  46. return message.message.format(**params)
  47. else:
  48. # Params not provided, return message as is
  49. return message.message
  50. return message.formatted
  51. def cache_set_nx(key, value, timeout: Optional[int] = 300) -> bool:
  52. """
  53. django-redis style cache set with nx, but with fallback for non-redis
  54. """
  55. try:
  56. return cache.set(key, value, timeout, nx=True)
  57. except TypeError:
  58. if cache.get(key):
  59. return False
  60. cache.set(key, value, timeout)
  61. return True