middleware.py 3.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. from __future__ import unicode_literals
  2. from datetime import timedelta
  3. import random
  4. import threading
  5. import uuid
  6. from django.conf import settings
  7. from django.db.models.signals import post_delete, post_save
  8. from django.utils import timezone
  9. from django.utils.functional import curry
  10. from extras.webhooks import enqueue_webhooks
  11. from .constants import (
  12. OBJECTCHANGE_ACTION_CREATE, OBJECTCHANGE_ACTION_DELETE, OBJECTCHANGE_ACTION_UPDATE,
  13. )
  14. from .models import ObjectChange
  15. _thread_locals = threading.local()
  16. def cache_changed_object(instance, **kwargs):
  17. action = OBJECTCHANGE_ACTION_CREATE if kwargs['created'] else OBJECTCHANGE_ACTION_UPDATE
  18. # Cache the object for further processing was the response has completed.
  19. _thread_locals.changed_objects.append(
  20. (instance, action)
  21. )
  22. def _record_object_deleted(request, instance, **kwargs):
  23. # Record that the object was deleted.
  24. if hasattr(instance, 'log_change'):
  25. instance.log_change(request.user, request.id, OBJECTCHANGE_ACTION_DELETE)
  26. enqueue_webhooks(instance, OBJECTCHANGE_ACTION_DELETE)
  27. class ObjectChangeMiddleware(object):
  28. """
  29. This middleware performs two functions in response to an object being created, updated, or deleted:
  30. 1. Create an ObjectChange to reflect the modification to the object in the changelog.
  31. 2. Enqueue any relevant webhooks.
  32. The post_save and pre_delete signals are employed to catch object modifications, however changes are recorded a bit
  33. differently for each. Objects being saved are cached into thread-local storage for action *after* the response has
  34. completed. This ensures that serialization of the object is performed only after any related objects (e.g. tags)
  35. have been created. Conversely, deletions are acted upon immediately, so that the serialized representation of the
  36. object is recorded before it (and any related objects) are actually deleted from the database.
  37. """
  38. def __init__(self, get_response):
  39. self.get_response = get_response
  40. def __call__(self, request):
  41. # Initialize an empty list to cache objects being saved.
  42. _thread_locals.changed_objects = []
  43. # Assign a random unique ID to the request. This will be used to associate multiple object changes made during
  44. # the same request.
  45. request.id = uuid.uuid4()
  46. # Signals don't include the request context, so we're currying it into the pre_delete function ahead of time.
  47. record_object_deleted = curry(_record_object_deleted, request)
  48. # Connect our receivers to the post_save and pre_delete signals.
  49. post_save.connect(cache_changed_object, dispatch_uid='record_object_saved')
  50. post_delete.connect(record_object_deleted, dispatch_uid='record_object_deleted')
  51. # Process the request
  52. response = self.get_response(request)
  53. # Create records for any cached objects that were created/updated.
  54. for obj, action in _thread_locals.changed_objects:
  55. # Record the change
  56. if hasattr(obj, 'log_change'):
  57. obj.log_change(request.user, request.id, action)
  58. # Enqueue webhooks
  59. enqueue_webhooks(obj, action)
  60. # Housekeeping: 1% chance of clearing out expired ObjectChanges
  61. if _thread_locals.changed_objects and settings.CHANGELOG_RETENTION and random.randint(1, 100) == 1:
  62. cutoff = timezone.now() - timedelta(days=settings.CHANGELOG_RETENTION)
  63. purged_count, _ = ObjectChange.objects.filter(
  64. time__lt=cutoff
  65. ).delete()
  66. return response