diff --git a/shynet/analytics/migrations/0008_session_is_bounce.py b/shynet/analytics/migrations/0008_session_is_bounce.py new file mode 100644 index 0000000..cbc7d34 --- /dev/null +++ b/shynet/analytics/migrations/0008_session_is_bounce.py @@ -0,0 +1,24 @@ +# Generated by Django 3.1.7 on 2021-03-28 21:38 + +from django.db.models.expressions import F +from ..models import Session, Hit +from django.db import migrations, models +from django.db.models import Subquery, OuterRef + +def update_bounce_stats(_a, _b): + Session.objects.all().annotate(hit_count=models.Count("hit")).filter(hit_count__gt=1).update(is_bounce=False) + +class Migration(migrations.Migration): + + dependencies = [ + ('analytics', '0007_auto_20210328_1634'), + ] + + operations = [ + migrations.AddField( + model_name='session', + name='is_bounce', + field=models.BooleanField(db_index=True, default=True), + ), + migrations.RunPython(update_bounce_stats, lambda: ()), + ] diff --git a/shynet/analytics/models.py b/shynet/analytics/models.py index 2776426..92d9106 100644 --- a/shynet/analytics/models.py +++ b/shynet/analytics/models.py @@ -49,6 +49,8 @@ class Session(models.Model): latitude = models.FloatField(null=True) time_zone = models.TextField(blank=True) + is_bounce = models.BooleanField(default=True, db_index=True) + class Meta: ordering = ["-start_time"] indexes = [ @@ -76,6 +78,12 @@ class Session(models.Model): kwargs={"pk": self.service.pk, "session_pk": self.uuid}, ) + def recalculate_bounce(self): + bounce = self.hit_set.count() == 1 + if bounce != self.is_bounce: + self.is_bounce = bounce + self.save() + class Hit(models.Model): session = models.ForeignKey(Session, on_delete=models.CASCADE, db_index=True) diff --git a/shynet/analytics/tasks.py b/shynet/analytics/tasks.py index b41bb29..d68ac58 100644 --- a/shynet/analytics/tasks.py +++ b/shynet/analytics/tasks.py @@ -186,6 +186,10 @@ def ingress_request( last_seen=time, service=service ) + + # Recalculate whether the session is a bounce + session.recalculate_bounce() + # Set idempotency (if applicable) if idempotency is not None: cache.set( diff --git a/shynet/core/models.py b/shynet/core/models.py index 596bf39..60bdb76 100644 --- a/shynet/core/models.py +++ b/shynet/core/models.py @@ -133,7 +133,7 @@ class Service(models.Model): ) hit_count = hits.count() - bounces = sessions.annotate(hit_count=models.Count("hit")).filter(hit_count=1) + bounces = sessions.filter(is_bounce=True) bounce_count = bounces.count() locations = (