middleware.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. import random
  2. import threading
  3. import uuid
  4. from datetime import timedelta
  5. from django.conf import settings
  6. from django.db.models.signals import post_delete, post_save
  7. from django.utils import timezone
  8. from django.utils.functional import curry
  9. from django_prometheus.models import model_deletes, model_inserts, model_updates
  10. from .constants import (
  11. OBJECTCHANGE_ACTION_CREATE, OBJECTCHANGE_ACTION_DELETE, OBJECTCHANGE_ACTION_UPDATE,
  12. )
  13. from .models import ObjectChange
  14. from .signals import purge_changelog
  15. from .webhooks import enqueue_webhooks
  16. _thread_locals = threading.local()
  17. def handle_changed_object(sender, instance, **kwargs):
  18. """
  19. Fires when an object is created or updated
  20. """
  21. # Queue the object and a new ObjectChange for processing once the request completes
  22. if hasattr(instance, 'to_objectchange'):
  23. action = OBJECTCHANGE_ACTION_CREATE if kwargs['created'] else OBJECTCHANGE_ACTION_UPDATE
  24. objectchange = instance.to_objectchange(action)
  25. _thread_locals.changed_objects.append(
  26. (instance, objectchange)
  27. )
  28. def _handle_deleted_object(request, sender, instance, **kwargs):
  29. """
  30. Fires when an object is deleted
  31. """
  32. # Record an Object Change
  33. if hasattr(instance, 'to_objectchange'):
  34. objectchange = instance.to_objectchange(OBJECTCHANGE_ACTION_DELETE)
  35. objectchange.user = request.user
  36. objectchange.request_id = request.id
  37. objectchange.save()
  38. # Enqueue webhooks
  39. enqueue_webhooks(instance, request.user, request.id, OBJECTCHANGE_ACTION_DELETE)
  40. # Increment metric counters
  41. model_deletes.labels(instance._meta.model_name).inc()
  42. def purge_objectchange_cache(sender, **kwargs):
  43. """
  44. Delete any queued object changes waiting to be written.
  45. """
  46. _thread_locals.changed_objects = []
  47. class ObjectChangeMiddleware(object):
  48. """
  49. This middleware performs three functions in response to an object being created, updated, or deleted:
  50. 1. Create an ObjectChange to reflect the modification to the object in the changelog.
  51. 2. Enqueue any relevant webhooks.
  52. 3. Increment the metric counter for the event type.
  53. The post_save and post_delete signals are employed to catch object modifications, however changes are recorded a bit
  54. differently for each. Objects being saved are cached into thread-local storage for action *after* the response has
  55. completed. This ensures that serialization of the object is performed only after any related objects (e.g. tags)
  56. have been created. Conversely, deletions are acted upon immediately, so that the serialized representation of the
  57. object is recorded before it (and any related objects) are actually deleted from the database.
  58. """
  59. def __init__(self, get_response):
  60. self.get_response = get_response
  61. def __call__(self, request):
  62. # Initialize an empty list to cache objects being saved.
  63. _thread_locals.changed_objects = []
  64. # Assign a random unique ID to the request. This will be used to associate multiple object changes made during
  65. # the same request.
  66. request.id = uuid.uuid4()
  67. # Signals don't include the request context, so we're currying it into the post_delete function ahead of time.
  68. handle_deleted_object = curry(_handle_deleted_object, request)
  69. # Connect our receivers to the post_save and post_delete signals.
  70. post_save.connect(handle_changed_object, dispatch_uid='cache_changed_object')
  71. post_delete.connect(handle_deleted_object, dispatch_uid='cache_deleted_object')
  72. # Provide a hook for purging the change cache
  73. purge_changelog.connect(purge_objectchange_cache)
  74. # Process the request
  75. response = self.get_response(request)
  76. # If the change cache is empty, there's nothing more we need to do.
  77. if not _thread_locals.changed_objects:
  78. return response
  79. # Create records for any cached objects that were created/updated.
  80. for obj, objectchange in _thread_locals.changed_objects:
  81. # Record the change
  82. objectchange.user = request.user
  83. objectchange.request_id = request.id
  84. objectchange.save()
  85. # Enqueue webhooks
  86. enqueue_webhooks(obj, request.user, request.id, objectchange.action)
  87. # Increment metric counters
  88. if objectchange.action == OBJECTCHANGE_ACTION_CREATE:
  89. model_inserts.labels(obj._meta.model_name).inc()
  90. elif objectchange.action == OBJECTCHANGE_ACTION_UPDATE:
  91. model_updates.labels(obj._meta.model_name).inc()
  92. # Housekeeping: 1% chance of clearing out expired ObjectChanges. This applies only to requests which result in
  93. # one or more changes being logged.
  94. if settings.CHANGELOG_RETENTION and random.randint(1, 100) == 1:
  95. cutoff = timezone.now() - timedelta(days=settings.CHANGELOG_RETENTION)
  96. purged_count, _ = ObjectChange.objects.filter(
  97. time__lt=cutoff
  98. ).delete()
  99. return response