Cache bounce

This commit is contained in:
R. Miles McCain 2021-03-28 21:55:38 +00:00
parent 518436ffd2
commit 02cbee5c8c
4 changed files with 37 additions and 1 deletions

View File

@ -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: ()),
]

View File

@ -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)

View File

@ -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(

View File

@ -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 = (