Skip to content

Commit 02cbee5

Browse files
committed
Cache bounce
1 parent 518436f commit 02cbee5

File tree

4 files changed

+37
-1
lines changed

4 files changed

+37
-1
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Generated by Django 3.1.7 on 2021-03-28 21:38
2+
3+
from django.db.models.expressions import F
4+
from ..models import Session, Hit
5+
from django.db import migrations, models
6+
from django.db.models import Subquery, OuterRef
7+
8+
def update_bounce_stats(_a, _b):
9+
Session.objects.all().annotate(hit_count=models.Count("hit")).filter(hit_count__gt=1).update(is_bounce=False)
10+
11+
class Migration(migrations.Migration):
12+
13+
dependencies = [
14+
('analytics', '0007_auto_20210328_1634'),
15+
]
16+
17+
operations = [
18+
migrations.AddField(
19+
model_name='session',
20+
name='is_bounce',
21+
field=models.BooleanField(db_index=True, default=True),
22+
),
23+
migrations.RunPython(update_bounce_stats, lambda: ()),
24+
]

shynet/analytics/models.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,8 @@ class Session(models.Model):
4949
latitude = models.FloatField(null=True)
5050
time_zone = models.TextField(blank=True)
5151

52+
is_bounce = models.BooleanField(default=True, db_index=True)
53+
5254
class Meta:
5355
ordering = ["-start_time"]
5456
indexes = [
@@ -76,6 +78,12 @@ def get_absolute_url(self):
7678
kwargs={"pk": self.service.pk, "session_pk": self.uuid},
7779
)
7880

81+
def recalculate_bounce(self):
82+
bounce = self.hit_set.count() == 1
83+
if bounce != self.is_bounce:
84+
self.is_bounce = bounce
85+
self.save()
86+
7987

8088
class Hit(models.Model):
8189
session = models.ForeignKey(Session, on_delete=models.CASCADE, db_index=True)

shynet/analytics/tasks.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,10 @@ def ingress_request(
186186
last_seen=time,
187187
service=service
188188
)
189+
190+
# Recalculate whether the session is a bounce
191+
session.recalculate_bounce()
192+
189193
# Set idempotency (if applicable)
190194
if idempotency is not None:
191195
cache.set(

shynet/core/models.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ def get_relative_stats(self, start_time, end_time):
133133
)
134134
hit_count = hits.count()
135135

136-
bounces = sessions.annotate(hit_count=models.Count("hit")).filter(hit_count=1)
136+
bounces = sessions.filter(is_bounce=True)
137137
bounce_count = bounces.count()
138138

139139
locations = (

0 commit comments

Comments
 (0)