Publish reviewed history-free open-source snapshot (2026-10-12)
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
from django.db import transaction
|
||||
from django.db.models import Sum
|
||||
from django.db.models.signals import post_delete, post_save
|
||||
from django.dispatch import receiver
|
||||
|
||||
from .models import Subscription, UsageRecord
|
||||
from .usage_accounting import lock_usage_subscriptions
|
||||
|
||||
|
||||
def recompute_subscription_usage(subscription_id):
|
||||
with transaction.atomic():
|
||||
lock_usage_subscriptions([subscription_id])
|
||||
# Aggregate AFTER acquiring the shared parent lock. Independent node
|
||||
# rows are not sufficient to serialize a subscription-wide total.
|
||||
totals = UsageRecord.objects.filter(subscription_id=subscription_id).aggregate(
|
||||
upload=Sum("upload_bytes"),
|
||||
download=Sum("download_bytes"),
|
||||
)
|
||||
Subscription.objects.filter(pk=subscription_id).update(
|
||||
upload_bytes=totals["upload"] or 0,
|
||||
download_bytes=totals["download"] or 0,
|
||||
)
|
||||
|
||||
|
||||
@receiver(post_save, sender=UsageRecord)
|
||||
def usage_saved(sender, instance, **kwargs):
|
||||
recompute_subscription_usage(instance.subscription_id)
|
||||
|
||||
|
||||
@receiver(post_delete, sender=UsageRecord)
|
||||
def usage_deleted(sender, instance, **kwargs):
|
||||
recompute_subscription_usage(instance.subscription_id)
|
||||
Reference in New Issue
Block a user