-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdataset_json.py
More file actions
2135 lines (1776 loc) · 76.3 KB
/
Copy pathdataset_json.py
File metadata and controls
2135 lines (1776 loc) · 76.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# MyTraL: my trailing log
#
# Copyright (C) 2015-2026 Martin Dvorak <martin.dvorak@mindforger.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
JSON-based persistence PURPOSE:
- it is meant for 1 user / desktop use (however, it can be used LOCALLY w/ >1 user)
- it is NOT meant for many users - RDBMS (embedded/cluster) is for that purpose
JSON-based persistence TENETS:
- MindForger persistence RULEZ ~ BEWARE changing files under running MyTraL server!
- SINGLE user
- when user logs in:
- ALL activity/settings/* are loaded
- lifelong is build in memory and stored to cache: [user] -> [filename key] -> [dict]
- settings are loaded to memory and stored in cache
- *-stats are build in memory and stored to cache
- data are READ from MEMORY ~ in-memory cache
- data are WRITTEN to FILESYSTEM through MEMORY (cache)
- lifelong is NOT persisted: it is considered to be an in memory index
- *-stats are NOT persisted: they are considered to be in memory indices
- CACHE is integral part of the JSON dataset, NOT other as they may have different needs
- CACHE is controlled by JSON dataset implementation to do its own OPTIMIZATIONS
JSON-based user activities dataset DESIGN:
- FILESYSTEM ~ file names:
- ACTIVITIES:
- activities-<YEAR>.json
- RESERVED file name
- activities are grouped by YEAR
- NEW activities are routed to its year file
- PROFILE:
- user-<SETTING>.json
- specific profile settings like gear, outfits, goals, routes, ...
- user-<SETTING>-stats.json
- LAZY: created on demand when needed
- stats calculated from ALL activities e.g. use of a given gear
- not all settings need stats files
- DIARY:
- diary-weekly-<YEAR>.json
- RESERVED file name
- no special treatment
- DIGITIZATION / WORKING / RAW ACTIVITIES:
- activities-<WHATEVER>.json
- NOT clashing with the RESERVED names of production JSON activity files
- invisible in non-expert mode
- in-memory CACHE ~ keys:
- see MytralCache for more details: activities, settings and indices (cache ONLY)
Dataset MODEs:
1. LIFELONG:
- default
- works on MULTIPLE activities-*.json files
- activities are routed to file by when year
2. CUSTOM ACTIVITIES DATASET:
- custom year / dataset
- works on SINGLE activities-*.json file
- no routing (the file is used), no lifelong (the file is lifelong itself)
"""
import dataclasses
import datetime
import json
import pathlib
import re
import uuid
from typing import Callable
from mytral import commons
from mytral import config
from mytral import loggers
from mytral import persistences
from mytral import security
from mytral import settings
from mytral import stats
from mytral.backends import cache
from mytral.backends import caches
from mytral.backends import dataset
from mytral.backends import entities
# constants
FILE_ACTIVITIES_PRE = "activities-"
FILE_STATS_INFIX = "stats"
EXT_JSON = "json"
def list_activity_dataset_names(user_dir: pathlib.Path) -> list[str]:
wild = user_dir.glob(f"{dataset.MyTraLDataset.PREFIX_DS_NAME}*.json")
names = [str(f.stem) for f in wild if f.is_file() and "user" not in str(f.stem)]
if (
JsonUsersDataset.FILE_DATASET_MAIN not in names
and (user_dir / f"{JsonUsersDataset.FILE_DATASET_MAIN}.json").exists()
):
names.append(JsonUsersDataset.FILE_DATASET_MAIN)
# always include lifelong as it's a symbolic/virtual dataset
if JsonUsersDataset.FILE_DATASET_MAIN not in names:
names.append(JsonUsersDataset.FILE_DATASET_MAIN)
return names
def list_activity_year_dataset_names(user_dir: pathlib.Path) -> list[str]:
activities_ds_names = list_activity_dataset_names(user_dir=user_dir)
if activities_ds_names:
pattern = r"^activities-\d{4}$"
year_ds_names = []
for a_ds_name in activities_ds_names:
if a_ds_name and bool(re.match(pattern, a_ds_name)):
year_ds_names.append(a_ds_name)
return year_ds_names
return activities_ds_names
# TODO rename JSONUser > JsonUser...
class JSONUserActivitiesDataset:
"""JSON implementation of user activities dataset.
Activities synchronization:
- In order to avoid race conditions in reading/writing the activities
w/ or w/o cache, all activity related methods are mutually exclusive,
including statistics.
"""
@staticmethod
def _ddict_2_dict(
activities: dict[str, dict] | list[dict],
) -> dict[str, entities.ActivityEntity]:
"""Convert dict (old) or list (new) format to runtime dict."""
# normalize to dict format for processing
activities_dict = persistences.normalize_dict_or_list_to_dict(activities)
user_ds_d = {}
for d in activities_dict.values():
# backward compatibility: migrate gear (str) to gears (list[str])
if "gear" in d and "gears" not in d:
gear_value = d.pop("gear")
if gear_value:
d["gears"] = [gear_value]
# backward compatibility: migrate legacy single recording keys
gpx_blob_key = d.pop("gpx_blob_key", "")
fit_blob_key = d.pop("fit_blob_key", "")
if "recorded_blob_keys" not in d or d["recorded_blob_keys"] is None:
d["recorded_blob_keys"] = []
if gpx_blob_key:
gpx_entry = f"{gpx_blob_key}.gpx"
if gpx_entry not in d["recorded_blob_keys"]:
d["recorded_blob_keys"].append(gpx_entry)
if fit_blob_key:
fit_entry = f"{fit_blob_key}.fit"
if fit_entry not in d["recorded_blob_keys"]:
d["recorded_blob_keys"].append(fit_entry)
entity = entities.ActivityEntity(**d)
entity.exercises = [entities.ExerciseEntity(**e) for e in entity.exercises]
entity.sickness_symptoms = [
entities.SicknessSymptomEntity(**e) for e in entity.sickness_symptoms
]
entity.laps = [
entities.LapEntity(**lap)
for lap in (entity.laps if entity.laps else [])
]
user_ds_d[entity.key] = entity
return user_ds_d
def __init__(
self,
mytral_config: config.MytralConfig,
key_generator: Callable[[], str],
data_dir: pathlib.Path,
ext: str,
mytral_cache: cache.MytralCache,
# TODO there is a bug: assert for None when_* > unit test load&safe&compare ALL
persistence_sparse: bool = False,
persistence_msgpack: bool = False,
logger: loggers.MytralLogger | None = None,
):
"""User activities dataset stored in text or binary JSON files.
Parameters
----------
mytral_config : config.MytralConfig
Application configuration.
key_generator : Callable[[], str]
Function to generate new unique keys for activities.
data_dir : pathlib.Path
Base directory where user data is stored.
ext : str
File extension to use for the dataset files (e.g., 'json').
mytral_cache : cache.MytralCacheAbc
Cache instance to use for caching user data - JSON persistence controls
the cache set/get/evict cycle as it is aware of modification (can evict
all the impacted indices) as well as when to read from memory and when
to write to filesystem through memory.
persistence_sparse : bool, optional
If True, save only non-default values in the dataset files to save space.
persistence_msgpack : bool
If True, use MessagePack format for persistence instead of plain JSON.
This class supports switching between JSON and MessagePack formats. The
logic works as follows when MessagePack is enabled:
- loading: if BOTH files exist, compare timestamps and load the newer one
- saving: save MessagePack file ONLY and delete the JSON file
If MessagePack is disabled, then JSON works analogously as MessagePack.
"""
self.logger = logger or loggers.MytralStructLogger()
self.log_name = "[JSON user activities]"
self.config = mytral_config
self.new_key = key_generator
self.data_dir = data_dir
self.ext = ext
# caching
self.cached_dataset_name = ""
self._cache = mytral_cache
# sparse mode: save only non-default values, complete on load
self.persistence_sparse = persistence_sparse
# persistence format: JSON (.json) vs. MessagePack (.msgpack)
self.persistence_msgpack = persistence_msgpack
@staticmethod
def _ds_name_for_activity(
dataset_name: str,
entity: entities.ActivityEntity | int,
) -> str:
"""Get (target) dataset name for given activity."""
when_year = entity if isinstance(entity, int) else entity.when_year
if commons.DS_LIFELONG == dataset_name:
upper_year_limit = datetime.date.today().year + 50
if not (1900 < when_year < upper_year_limit):
raise RuntimeError(
f"Activity's year is out of range: '{when_year}', most "
f"probably an error and therefore the activity cannot be saved, "
f"because such dataset file does NOT exist and will not be created."
)
return f"{FILE_ACTIVITIES_PRE}{when_year}"
# else SINGLE dataset
return dataset_name
def _ds_path(
self, user_id: str, dataset_name: str, ext: str = persistences.EXT_JSON
) -> pathlib.Path:
return self.data_dir / user_id / f"{dataset_name}.{ext}"
def _ds_stats_path(
self, user_id: str, dataset_name: str, ext: str = persistences.EXT_JSON
) -> pathlib.Path:
return self.data_dir / user_id / f"{dataset_name}-{FILE_STATS_INFIX}.{ext}"
def _dict_2_ddict(
self, activities: dict[str, entities.ActivityEntity]
) -> list[dict]:
"""Dict of entities to list of dicts (new format)."""
if self.persistence_sparse:
return [a.to_sparse_dict() for a in activities.values()]
return [dataclasses.asdict(a) for a in activities.values()]
def user_dir(self, user_id: str) -> pathlib.Path:
user_dir = self.data_dir / user_id
user_dir.mkdir(parents=True, exist_ok=True)
return user_dir
#
# CACHE mgmt
#
def _lifelong_cache_refresh(self, user_id: str, dataset_name: str) -> dict:
self.logger.info(
f" {self.log_name} REFRESH '{dataset_name}' dataset to CACHE..."
)
lifelong_ds = {}
years_cache = self._cache.user(user_id).activities_years()
for y_ds in years_cache:
lifelong_ds.update(years_cache[y_ds])
self._cache.user(user_id).set_activities(
activities=lifelong_ds, dataset_name=dataset_name
)
self.logger.info(
f" {self.log_name} DONE '{dataset_name}' dataset CACHED with "
f"{len(lifelong_ds)} activities"
)
return lifelong_ds
#
# CACHE through CRUD
#
def _load(
self, user_id: str, dataset_name: str
) -> dict[str, entities.ActivityEntity]:
"""Load LIFELONG/custom activities either from cache or from the filesystem
(to the cache).
- Initializes NON-INITIALIZED cache by loading all YEAR activities files
and refreshing LIFELONG/custom by merging YEARs there.
Returns
-------
dict :
LIFELONG/custom activities' dataset.
"""
# INVARIANT: profile and settings are loaded in cache
# CACHE initialization ~ load YEAR files || CUSTOM file
user_cache = self._cache.user(user_id)
if user_cache.dataset_name() != dataset_name:
self.logger.info(
f"{self.log_name} INITIALIZING cache on the dataset change: "
f"'{user_cache.dataset_name()}' -> '{dataset_name}'"
)
# dataset NOT yet loaded OR switched
user_cache.evict_activities()
user_cache.set_dataset_name(dataset_name)
# INITIALIZE the cache by loading data from the filesystem
if commons.DS_LIFELONG == dataset_name:
year_a_ds_names = list_activity_year_dataset_names(
user_dir=self.user_dir(user_id=user_id)
)
year_a_cache_dict = user_cache.activities_years()
for year_a_ds_name in year_a_ds_names:
year_str = year_a_ds_name[11:]
if not year_str:
raise RuntimeError(
f"Unable to extract year from '{year_a_ds_names}' when "
f"initializing JSON cache"
)
year_ds_path = self._ds_path(user_id, year_a_ds_name)
if not year_ds_path.exists():
year_ds_dd: dict = {}
else:
year_ds_dd = persistences.load_json(year_ds_path)
year_activities = JSONUserActivitiesDataset._ddict_2_dict(
year_ds_dd
)
year_a_cache_dict[year_str] = year_activities
self.logger.info(
f"{self.log_name} '{year_str}' ({len(year_activities)}) "
f"activities loaded to cache"
)
else: # custom dataset
self.logger.info(f"{self.log_name} custom dataset - no year cache data")
# cache INITIALIZED
user_cache.set_dataset_name(dataset_name=dataset_name)
# LIFELONG dataset
all_activities = self._cache.user(user_id).activities(dataset_name)
if not all_activities:
all_activities = self._lifelong_cache_refresh(
user_id=user_id, dataset_name=dataset_name
)
return all_activities
def _exists(self, user_id: str, dataset_name: str) -> bool:
return self._ds_path(user_id=user_id, dataset_name=dataset_name).exists()
def _save(self, ds: dict[str, dict], user_id: str, dataset_name: str):
persistences.save_json(
file_path=self._ds_path(user_id=user_id, dataset_name=dataset_name),
data_dict=ds,
)
def create_dataset(self, user_id: str, dataset_name: str):
if self._exists(user_id=user_id, dataset_name=dataset_name):
raise ValueError(
f"{self.log_name} Dataset '{dataset_name}' already exists for user "
f"{user_id}"
)
self._save(
ds=self._dict_2_ddict({}),
user_id=user_id,
dataset_name=dataset_name,
)
def delete_dataset(self, user_id: str, dataset_name: str):
if not self._exists(user_id=user_id, dataset_name=dataset_name):
raise ValueError(
f"{self.log_name} Unable to delete dataset '{dataset_name}' for user "
f"{user_id} as it does not exist"
)
ds_path = self._ds_path(user_id=user_id, dataset_name=dataset_name)
ds_path.unlink()
def _pre_modify_activity(
self,
user_id: str,
dataset_name: str,
entity: entities.ActivityEntity | int,
) -> tuple[dict, str]:
# assess target dataset name from the when_year
target_dataset_name = self._ds_name_for_activity(
dataset_name=dataset_name,
entity=entity,
)
# YEAR
# load YEAR datasets from filesystem to cache, refresh LIFELONG/CUSTOM
self._load(user_id=user_id, dataset_name=dataset_name)
# get YEAR dataset from cache
year_ds = self._cache.user(user_id=user_id).activities_year(target_dataset_name)
return year_ds, target_dataset_name
def _post_modify_activity(
self,
user_id: str,
dataset_name: str,
target_dataset_name: str,
entity: entities.ActivityEntity,
year_ds: dict,
):
# write YEAR dataset to filesystem || CUSTOM dataset file
self._save(
ds=self._dict_2_ddict(activities=year_ds),
user_id=user_id,
dataset_name=target_dataset_name,
)
# LIFELONG (in-memory only)
lifelong_ds = self._cache.user(user_id=user_id).activities(
dataset_name=dataset_name
)
lifelong_ds[entity.key] = entity # add/set, do not re-merge all YEARS - faster
# update YEAR cache -> evict indices
self._cache.user(user_id).evict_on_activity_cud()
# update component usage if activity has gear
if hasattr(entity, "gears") and entity.gears:
for gear_key in entity.gears:
self._update_gear_component_usage(
user_id=user_id,
dataset_name=dataset_name,
gear_key=gear_key,
activity_distance_meters=entity.distance or 0,
activity_time_seconds=entity.duration_seconds or 0,
activity_timestamp=entity.when or "",
)
def _update_gear_component_usage(
self,
user_id: str,
dataset_name: str,
gear_key: str,
activity_distance_meters: int,
activity_time_seconds: int,
activity_timestamp: str,
):
"""Update usage for all active components of a gear based on an activity."""
try:
# get gear
gear = self._parent.get_gear(
user_id=user_id, key=gear_key, dataset_name=dataset_name
)
if not gear or not gear.components:
return
# check if this activity is newer than last processed
if (
gear.last_activity_processed
and activity_timestamp <= gear.last_activity_processed
):
return # already processed
# update all active components
for component_dict in gear.components:
if component_dict.get("status") == "active":
component_dict["distance_meters"] = (
component_dict.get("distance_meters", 0)
+ activity_distance_meters
)
component_dict["time_seconds"] = (
component_dict.get("time_seconds", 0) + activity_time_seconds
)
# update last processed timestamp
if (
not gear.last_activity_processed
or activity_timestamp > gear.last_activity_processed
):
gear.last_activity_processed = activity_timestamp
# save gear
self._parent.update_gear(
user_id=user_id, gear=gear, dataset_name=dataset_name
)
except Exception:
# silently fail - don't break activity creation if gear update fails
pass
def create_activity(
self,
user_id: str,
dataset_name: str,
entity: entities.ActivityEntity,
) -> entities.ActivityEntity:
"""Create a new entity:
- resolve target dataset file
- cache:
- evict what needs to be evicted on modification:
lifelong, stats, settings stats, ...
- add activity to cached dataset for YEAR
- add activity to cached LIFELONG dataset
? let build settings stats (which depend on activities) vs. on-demand
Parameters
----------
user_id : str
User ID.
dataset_name : str
Dataset is either `lifelong` or a custom dataset - which determines mode
and routing of activities to dataset activities files.
entity: entities.ActivityEntity
Activity to be saved.
"""
# complete and validate activity
entity.key = self.new_key()
# TODO IMPROVE verification:
# - sort codes must not clash
# - keys must be unique
# - ...
entities.evaluate_activity(entity)
year_ds, target_dataset_name = self._pre_modify_activity(
user_id=user_id, dataset_name=dataset_name, entity=entity
)
# add entity to YEAR dataset
year_ds[entity.key] = entity
self._post_modify_activity(
user_id=user_id,
dataset_name=dataset_name,
target_dataset_name=target_dataset_name,
entity=entity,
year_ds=year_ds,
)
return entity
def create_activities(
self,
user_id: str,
dataset_name: str,
entity_list: list[entities.ActivityEntity],
) -> list[entities.ActivityEntity]:
"""Bulk creation of activities:
- activities are clustered by year
- activities w/ the same year are routed to their target dataset files for year
"""
result: list[entities.ActivityEntity] = []
today = datetime.datetime.now()
# STEP: cluster activities by year
a2year: dict[int, list[entities.ActivityEntity]] = {}
for e in entity_list:
when_year = e.when_year if isinstance(e.when_year, int) else today.year
upper_year_limit = datetime.date.today().year + 50
if not (1900 < when_year < upper_year_limit):
raise RuntimeError(
f"Activity's year is out of range: '{when_year}', most "
f"probably an error and therefore the activity cannot be saved, "
f"because such dataset file does NOT exist and will not be created."
)
if when_year not in a2year:
a2year[when_year] = []
a2year[when_year].append(e)
# STEP: get datasets for years > save clusters
for y in a2year:
pivot_a = a2year[y][0]
target_dataset_name = self._ds_name_for_activity(
dataset_name=dataset_name,
entity=pivot_a,
)
# load YEAR datasets from filesystem to cache, refresh LIFELONG/CUSTOM
self._load(user_id=user_id, dataset_name=dataset_name)
# get YEAR dataset from cache
year_ds = self._cache.user(user_id=user_id).activities_year(
target_dataset_name
)
# STEP: add ALL activities of the year to the YEAR dataset
for a in a2year[y]:
year_ds[a.key] = a
result.append(a)
# STEP: exactly 1 write per YEAR dataset to filesystem || CUSTOM ds file
self._save(
ds=self._dict_2_ddict(activities=year_ds),
user_id=user_id,
dataset_name=target_dataset_name,
)
# LIFELONG (in-memory only)
lifelong_ds = self._cache.user(user_id=user_id).activities(
dataset_name=dataset_name
)
for a in a2year[y]:
lifelong_ds[a.key] = a # add/set, do not re-merge all YEARS - faster
# STEP: update gear / component usage
# - IMPROVE: consider checking whether activities even has a gear
if a.gears:
for gear_key in a.gears:
self._update_gear_component_usage(
user_id=user_id,
dataset_name=dataset_name,
gear_key=gear_key,
activity_distance_meters=a.distance or 0,
activity_time_seconds=a.duration_seconds or 0,
activity_timestamp=a.when or "",
)
# STEP: on behalf of ALL years - update YEAR caches -> evict indices
self._cache.user(user_id).evict_on_activity_cud()
return result
def update_activity(
self,
user_id: str,
dataset_name: str,
entity: entities.ActivityEntity,
) -> entities.ActivityEntity:
# evaluate activity to calculate duration and other transient fields
entities.evaluate_activity(entity)
year_ds, target_dataset_name = self._pre_modify_activity(
user_id=user_id, dataset_name=dataset_name, entity=entity
)
if entity.key not in year_ds:
lifelong_ds = self._cache.user(user_id=user_id).activities(
dataset_name=dataset_name
)
if entity.key not in lifelong_ds:
raise ValueError(
f"Unable to find the activity to update - {entity.key} not found "
f"in activities datasets"
)
old_when_year = lifelong_ds[entity.key].when_year
old_target_dataset_name = self._ds_name_for_activity(
dataset_name=dataset_name,
entity=old_when_year,
)
old_year_ds = self._cache.user(user_id=user_id).activities_year(
old_target_dataset_name
)
if entity.key in old_year_ds:
del old_year_ds[entity.key]
# write old YEAR dataset to filesystem || CUSTOM dataset file
self._save(
ds=self._dict_2_ddict(activities=old_year_ds),
user_id=user_id,
dataset_name=old_target_dataset_name,
)
# set entity to YEAR dataset
year_ds[entity.key] = entity
self._post_modify_activity(
user_id=user_id,
dataset_name=dataset_name,
target_dataset_name=target_dataset_name,
entity=entity,
year_ds=year_ds,
)
return entity
def update_activities(
self, user_id: str, dataset_name: str, activities: list[entities.ActivityEntity]
):
"""Bulk update of activities:
- activities are evaluated to calculate duration and other transient fields
- activities are clustered by year
- activities w/ the same year are routed to their target dataset files for year
"""
# evaluate activities to calculate duration and other transient fields
for activity in activities:
entities.evaluate_activity(activity)
today = datetime.datetime.now()
# STEP: cluster activities by year
a2year: dict[int, list[entities.ActivityEntity]] = {}
for e in activities:
when_year = e.when_year if isinstance(e.when_year, int) else today.year
upper_year_limit = datetime.date.today().year + 50
if not (1900 < when_year < upper_year_limit):
raise RuntimeError(
f"Activity's year is out of range: '{when_year}', most "
f"probably an error and therefore the activity cannot be saved, "
f"because such dataset file does NOT exist and will not be created."
)
if when_year not in a2year:
a2year[when_year] = []
a2year[when_year].append(e)
# STEP: get datasets for years > save clusters
for y in a2year:
pivot_a = a2year[y][0]
target_dataset_name = self._ds_name_for_activity(
dataset_name=dataset_name,
entity=pivot_a,
)
# load YEAR datasets from filesystem to cache, refresh LIFELONG/CUSTOM
self._load(user_id=user_id, dataset_name=dataset_name)
# get YEAR dataset from cache
year_ds = self._cache.user(user_id=user_id).activities_year(
target_dataset_name
)
# STEP: add ALL activities of the year to the YEAR dataset
for a in a2year[y]:
year_ds[a.key] = a
# STEP: exactly 1 write per YEAR dataset to filesystem || CUSTOM ds file
self._save(
ds=self._dict_2_ddict(activities=year_ds),
user_id=user_id,
dataset_name=target_dataset_name,
)
# LIFELONG (in-memory only)
lifelong_ds = self._cache.user(user_id=user_id).activities(
dataset_name=dataset_name
)
for a in a2year[y]:
lifelong_ds[a.key] = a # add/set, do not re-merge all YEARS - faster
# STEP: update gear / component usage
if a.gears:
for gear_key in a.gears:
self._update_gear_component_usage(
user_id=user_id,
dataset_name=dataset_name,
gear_key=gear_key,
activity_distance_meters=a.distance or 0,
activity_time_seconds=a.duration_seconds or 0,
activity_timestamp=a.when or "",
)
# STEP: on behalf of ALL years - update YEAR caches -> evict indices
self._cache.user(user_id).evict_on_activity_cud()
def delete_activity(self, user_id: str, dataset_name: str, key: str) -> None:
# load YEAR datasets from filesystem to cache, refresh LIFELONG/CUSTOM
lifelong_ds = self._load(user_id=user_id, dataset_name=dataset_name)
if key not in lifelong_ds:
raise ValueError(
f"Unable to find the activity to delete - {key} not found in LIFELONG "
f"dataset w/ {len(lifelong_ds)} activities"
)
# YEAR dataset (filesystem)
entity = lifelong_ds[key]
year_ds, target_dataset_name = self._pre_modify_activity(
user_id=user_id, dataset_name=dataset_name, entity=entity
)
del year_ds[key]
self._save(
ds=self._dict_2_ddict(activities=year_ds),
user_id=user_id,
dataset_name=target_dataset_name,
)
# LIFELONG (in-memory only) - use already loaded lifelong_ds to avoid
# re-fetch returning empty dict in passthrough cache mode
if key in lifelong_ds:
del lifelong_ds[key]
# INVALIDATE cache
self._cache.user(user_id).evict_on_activity_cud()
def get_activity(
self, user_id: str, dataset_name: str, key: str
) -> entities.ActivityEntity:
user_ds_d = self._load(user_id=user_id, dataset_name=dataset_name)
if key not in user_ds_d:
raise ValueError(
f"Unable to get activity - activity with key '{key}' not found in "
f"the JSON database"
)
return user_ds_d[key]
def list_activities(
self,
user_id: str,
dataset_name: str,
filter_year: int = 0,
filter_month: int = 0,
filter_day: int = 0,
skip_future: bool = False,
) -> dict[str, entities.ActivityEntity]:
user_ds_d = self._load(user_id=user_id, dataset_name=dataset_name)
today = datetime.datetime.now()
activities = {}
for a in user_ds_d.values():
if filter_year and a.when_year != filter_year:
continue
if filter_month and a.when_month != filter_month:
continue
if filter_day and a.when_day != filter_day:
continue
if skip_future and (
a.when_year > today.year
or (a.when_year >= today.year and a.when_month > today.month)
or (
a.when_year >= today.year
and a.when_month >= today.month
and a.when_day > today.day
)
):
continue
activities[a.key] = a
return activities
def export_activities(
self,
user_id: str,
dataset_name: str,
) -> str:
user_ds_d = self._load(user_id=user_id, dataset_name=dataset_name)
return json.dumps(
self._dict_2_ddict(activities=user_ds_d),
indent=4,
)
class JsonUsersDataset(dataset.UserDataset, cache.MytralCacheInitializer):
"""Users dataset stored in JSON files:
- JSON users dataset is stateless in a sense that user ID must be provided as
parameter to all the methods.
- At the same time, JSON users dataset internal performs CACHING of the data for
individual users.
"""
DIR_DATA = "data"
FILE_DATASET_MAIN = commons.DATASET_NAME_MAIN
FILE_STRAVA_GEAR = "user-gear-strava.json"
FILE_USER_ACTIVITY_TYPES = "user-activity-types.json"
FILE_USER_EXERCISES = "user-exercises.json"
FILE_USER_GEAR = "user-gear.json"
FILE_USER_GOALS = "user-goals.json"
FILE_USER_LAPS = "user-laps.json"
FILE_USER_OUTFITS = "user-outfits.json"
FILE_USER_BOOKMARKS = "user-activity-bookmarks.json"
FILE_USER_COMPONENT_TEMPLATES = "user-component-templates.json"
FILE_USER_SETTINGS = "user-settings.json"
FILE_USER_SYMPTOMS = "user-symptoms.json"
def __init__(self):
"""User dataset constructor."""
dataset.UserDataset.__init__(self)
self.config = None
self.base_dir = None
self.data_dir = None
self.db_ext = None
# cache:
# - in-memory OR pass-through
# - CANNOT be accessed from outside to prevent race conditions
self._cache = None
# activities dataset ~ avoids huge module ~ implemented in friendly class
self._activities_dataset = None
self.log_name = "[JSON user dataset]"
def configure(
self,
mytral_config: config.MytralConfig,
logger: loggers.MytralLogger | None = None,
) -> None:
dataset.UserDataset.configure(self, mytral_config=mytral_config, logger=logger)
# select cache implementation based on configuration
if mytral_config.persistence_cache:
self._cache = caches.InMemoryMytralCache(
cache_initializer=self, logger=self.logger
)
else:
self._cache = caches.PassthroughMytralCache(
cache_initializer=self, logger=self.logger
)
# base directory (parent of the application data directory)
self.base_dir = self.config.persistence_data_dir
if not self.base_dir:
self.base_dir = pathlib.Path().absolute() # cwd
self.base_dir = (
self.base_dir
if isinstance(self.base_dir, pathlib.Path)
else pathlib.Path(self.base_dir)
)
if not self.base_dir.exists():
raise ValueError(
f"Specified application working directory '{self.base_dir}' does not "
f"exist"
)
self.logger.info(f"Using data directory: {self.base_dir}")
# application data directory
self.data_dir = self.base_dir / JsonUsersDataset.DIR_DATA
self.data_dir.mkdir(parents=True, exist_ok=True)
self.db_ext = persistences.EXT_CSV
# activities dataset
self._activities_dataset = JSONUserActivitiesDataset(
mytral_config=mytral_config,
key_generator=self.create_key,
data_dir=self.data_dir,
ext=self.db_ext,
mytral_cache=self._cache,
logger=self.logger,
)
def create_key(self) -> str:
return str(uuid.uuid4())
#
# files and dirs
#
def user_dir(self, user_id: str) -> pathlib.Path:
user_dir = self.data_dir / user_id
user_dir.mkdir(parents=True, exist_ok=True)
return user_dir
def user_settings_path(
self,
user_id: str = commons.DEFAULT_USER_NAME,
):
user_dir = self.user_dir(user_id)
return user_dir / JsonUsersDataset.FILE_USER_SETTINGS
def user_gear_path(self, user_id: str) -> pathlib.Path:
return self.user_dir(user_id) / JsonUsersDataset.FILE_USER_GEAR