Skip to content

Commit

Permalink
Merge pull request #300 from jeffreykirchner/dev
Browse files Browse the repository at this point in the history
cache replays.
  • Loading branch information
jeffreykirchner authored Jun 10, 2024
2 parents 60b4a2a + 954ee8a commit 1954022
Show file tree
Hide file tree
Showing 12 changed files with 55 additions and 31 deletions.
Binary file added database_dumps/trade_gifts.sql
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,9 @@ def take_refresh_screens(session_id, data):
session = Session.objects.get(id=session_id)
session.parameter_set.json(update_required=True)

session.replay_data = None
session.save()

except ObjectDoesNotExist:
logger.warning(f"take_refresh_screens session not found: {session_id}")
return {"status":"fail",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def take_get_session(session_key):
logger.info(f"take_get_session {session_key}")

try:
session = Session.objects.get(session_key=session_key)
session = Session.objects.defer("replay_data").get(session_key=session_key)
return session.json()
except ObjectDoesNotExist:
logger.warning(f"staff get_session session, not found: {session_key}")
Expand Down
32 changes: 18 additions & 14 deletions main/consumers/staff/session_consumer_mixins/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,28 +27,32 @@ async def load_session_events(self, event):
'''
load session for replay
'''
session_events = {}

session = await Session.objects.aget(id=self.session_id)
session_events_local = {}

if session.replay_data:
session_events_local = session.replay_data
else:
async for i in session.session_periods.all():

async for i in session.session_periods.all():
session_events_local[str(i.period_number)] = {}

session_events[str(i.period_number)] = {}
total_period_length = self.parameter_set_local["period_length"]

total_period_length = self.parameter_set_local["period_length"]
if i.period_number % self.parameter_set_local["break_frequency"] == 0:
total_period_length += self.parameter_set_local["break_length"]

if i.period_number % self.parameter_set_local["break_frequency"] == 0:
total_period_length += self.parameter_set_local["break_length"]
for j in range(total_period_length+1):
session_events_local[str(i.period_number)][str(j)] = []

for j in range(total_period_length+1):
session_events[str(i.period_number)][str(j)] = []
async for i in session.session_events.exclude(type="help_doc"):
v = {"type" : i.type, "data" : i.data}
session_events_local[str(i.period_number)][str(i.time_remaining)].append(v)

async for i in session.session_events.all():
v = {"type" : i.type, "data" : i.data}
# period_id = self.world_state_local["session_periods_order"][i.period_number-1]
session_events[str(i.period_number)][str(i.time_remaining)].append(v)
session.replay_data = session_events_local
await session.asave()

result = {"session_events": session_events}
result = {"session_events": session_events_local}

await self.send_message(message_to_self=result, message_to_group=None,
message_type=event['type'], send_to_client=True, send_to_group=False)
Expand Down
2 changes: 1 addition & 1 deletion main/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ def wrap(request, *args, **kwargs):
logger = logging.getLogger(__name__)
logger.info(f"user_is_owner {args} {kwargs}")

session = Session.objects.get(id=kwargs['pk'])
session = Session.objects.only("creator","collaborators").get(id=kwargs['pk'])

if request.user == session.creator or \
request.user.is_superuser or \
Expand Down
3 changes: 2 additions & 1 deletion main/forms/import_parameters_form.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user', None)
self.session_id = kwargs.pop('session_id', None)
super(ImportParametersForm, self).__init__(*args, **kwargs)
self.fields['session'].queryset = Session.objects.filter(soft_delete=False) \
self.fields['session'].queryset = Session.objects.only('title','creator', 'shared', 'collaborators')\
.filter(soft_delete=False) \
.exclude(id=self.session_id) \
.filter(Q(creator=self.user) | Q(shared=True) | Q(collaborators=self.user))\
.distinct() \
Expand Down
2 changes: 1 addition & 1 deletion main/forms/session_form_admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,5 +48,5 @@ class SessionFormAdmin(forms.ModelForm):
class Meta:
model=Session
fields = ('parameter_set', 'creator', 'collaborators', 'current_experiment_phase', 'title',
'world_state', 'world_state_avatars', 'started', 'shared', 'locked', 'id_string',
'world_state', 'replay_data', 'world_state_avatars', 'started', 'shared', 'locked', 'id_string',
'soft_delete', 'controlling_channel')
19 changes: 19 additions & 0 deletions main/migrations/0130_session_replay_data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Generated by Django 4.2.13 on 2024-06-10 21:18

import django.core.serializers.json
from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('main', '0129_session_id_string'),
]

operations = [
migrations.AddField(
model_name='session',
name='replay_data',
field=models.JSONField(blank=True, encoder=django.core.serializers.json.DjangoJSONEncoder, null=True, verbose_name='Replay Data'),
),
]
3 changes: 3 additions & 0 deletions main/models/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ class Session(models.Model):

# summary_data = models.JSONField(encoder=DjangoJSONEncoder, null=True, blank=True, verbose_name="Summary Data") #summary data for session

replay_data = models.JSONField(encoder=DjangoJSONEncoder, null=True, blank=True, verbose_name="Replay Data") #replay data for session

soft_delete = models.BooleanField(default=False) #hide session if true

timestamp = models.DateTimeField(auto_now_add=True)
Expand Down Expand Up @@ -327,6 +329,7 @@ def reset_experiment(self):
#self.timer_running = False
self.world_state ={}
self.world_state_avatars ={}
self.replay_data = None
self.save()

for p in self.session_players.all():
Expand Down
2 changes: 1 addition & 1 deletion main/views/staff/staff_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def get(self, request, *args, **kwargs):

parameters = Parameters.objects.first()

session = self.get_object()
session = Session.objects.only("id", "parameter_set").get(id=self.kwargs['pk'])

staff_edit_name_etc_form_ids=[]
for i in StaffEditNameEtcForm():
Expand Down
2 changes: 1 addition & 1 deletion main/views/staff/staff_session_parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def get(self, request, *args, **kwargs):
'''
handle get requests
'''
session = self.get_object()
session = Session.objects.only("id", "parameter_set").get(id=self.kwargs['pk'])

parameter_set_form = ParameterSetForm()
parameter_set_player_form = ParameterSetPlayerForm()
Expand Down
16 changes: 5 additions & 11 deletions setup.sh
Original file line number Diff line number Diff line change
@@ -1,14 +1,8 @@
echo "setup template"
echo "setup trade_gifts"
sudo service postgresql restart
echo "drop template db: enter db password"
dropdb trade_gifts -U dbadmin -h localhost -i
dropdb trade_gifts -U dbadmin -h localhost -i -p 5433
echo "create database: enter db password"
createdb -h localhost -U dbadmin -O dbadmin trade_gifts
source _trade_gifts_env/bin/activate
python manage.py migrate
echo "create super user"
python manage.py createsuperuser
echo "load fixtures"
python manage.py loaddata main.json
echo "setup done"
python manage.py runserver
createdb -h localhost -p 5433 -U dbadmin -O dbadmin trade_gifts
echo "restore database: enter db password"
pg_restore -v --no-owner --role=dbowner --host=localhost --port=5433 --username=dbadmin --dbname=trade_gifts database_dumps/trade_gifts.sql

0 comments on commit 1954022

Please sign in to comment.