Skip to content

Commit

Permalink
Cache bounce
Browse files Browse the repository at this point in the history
  • Loading branch information
milesmcc committed Mar 28, 2021
1 parent 518436f commit 02cbee5
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 1 deletion.
24 changes: 24 additions & 0 deletions shynet/analytics/migrations/0008_session_is_bounce.py
Original file line number Diff line number Diff line change
@@ -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: ()),
]
8 changes: 8 additions & 0 deletions shynet/analytics/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand Down Expand Up @@ -76,6 +78,12 @@ def get_absolute_url(self):
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)
Expand Down
4 changes: 4 additions & 0 deletions shynet/analytics/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
2 changes: 1 addition & 1 deletion shynet/core/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ def get_relative_stats(self, start_time, end_time):
)
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 = (
Expand Down

0 comments on commit 02cbee5

Please sign in to comment.