11import json
2+ from datetime import timedelta
23
4+ import arrow
35from implicitdict import ImplicitDict , Optional
46
7+ from monitoring .mock_uss .app import webapp
58from monitoring .monitorlib .multiprocessing import SynchronizedValue
69from monitoring .monitorlib .rid_automated_testing import injection_api
710
811from .behavior import ServiceProviderBehavior
912from .user_notifications import ServiceProviderUserNotifications
1013
14+ DB_CLEANUP_INTERVAL = timedelta (hours = 1 )
15+ FLIGHTS_LIMIT = timedelta (hours = 1 )
16+ NOTIFICATIONS_LIMIT = timedelta (hours = 1 )
17+
1118
1219class TestRecord (ImplicitDict ):
1320 """Representation of RID SP's record of a set of injected test flights"""
@@ -25,6 +32,14 @@ def __init__(self, **kwargs):
2532
2633 super ().__init__ (** kwargs )
2734
35+ def cleanup_flights (self ):
36+ self .flights = [
37+ flight
38+ for flight in self .flights
39+ if flight .get_span ()[1 ]
40+ and flight .get_span ()[1 ] + FLIGHTS_LIMIT > arrow .utcnow ().datetime # pyright: ignore[reportOptionalOperand]
41+ ]
42+
2843
2944class Database (ImplicitDict ):
3045 """Simple pseudo-database structure tracking the state of the mock system"""
@@ -33,8 +48,36 @@ class Database(ImplicitDict):
3348 behavior : ServiceProviderBehavior = ServiceProviderBehavior ()
3449 notifications : ServiceProviderUserNotifications = ServiceProviderUserNotifications ()
3550
51+ def cleanup_notifications (self ):
52+ self .notifications .cleanup (NOTIFICATIONS_LIMIT )
53+
54+ def cleanup_flights (self ):
55+ to_cleanup = []
56+
57+ for test_id , test in self .tests .items ():
58+ if test .flights :
59+ test .cleanup_flights ()
60+
61+ if not test .flights :
62+ to_cleanup .append (test_id )
63+
64+ for test_id in to_cleanup :
65+ del self .tests [test_id ]
66+
3667
3768db = SynchronizedValue [Database ](
3869 Database (),
3970 decoder = lambda b : ImplicitDict .parse (json .loads (b .decode ("utf-8" )), Database ),
4071)
72+
73+ TASK_DATABASE_CLEANUP = "ridsp database cleanup"
74+
75+
76+ @webapp .periodic_task (TASK_DATABASE_CLEANUP )
77+ def database_cleanup () -> None :
78+ with db .transact () as tx :
79+ tx .value .cleanup_notifications ()
80+ tx .value .cleanup_flights ()
81+
82+
83+ webapp .set_task_period (TASK_DATABASE_CLEANUP , DB_CLEANUP_INTERVAL )
0 commit comments