Skip to content

Commit 8f1caf8

Browse files
Reduce interaction with database when the instrument has no recent data
1 parent 47449aa commit 8f1caf8

File tree

1 file changed

+35
-2
lines changed

1 file changed

+35
-2
lines changed

src/webmon_app/reporting/report/view_util.py

+35-2
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,14 @@ def processing_request(request, instrument, run_id, destination):
219219
return redirect(reverse("report:detail", args=[instrument, run_id]))
220220

221221

222+
def __generate_empty_rates(n_hours):
223+
runs = []
224+
num_runs = 0 # there are no runs
225+
for i in range(n_hours):
226+
runs.append([-i, num_runs])
227+
return runs
228+
229+
222230
def retrieve_rates(instrument_id, last_run_id):
223231
"""
224232
Retrieve the run rate and error rate for an instrument.
@@ -227,6 +235,8 @@ def retrieve_rates(instrument_id, last_run_id):
227235
:param instrument_id: Instrument object
228236
:param last_run_id: DataRun object
229237
"""
238+
n_hours = 24
239+
230240
last_run = None
231241
if last_run_id is not None:
232242
last_run = last_run_id.run_number
@@ -249,14 +259,37 @@ def _get_rate(id_name):
249259

250260
# If we didn't find good rates in the cache, recalculate them
251261
if runs is None or errors is None:
252-
runs = run_rate(instrument_id)
253-
errors = error_rate(instrument_id)
262+
# check for any run in the last n-hours
263+
time_oldest = timezone.now() - datetime.timedelta(hours=n_hours + 1) # is +1 needed?
264+
265+
# only query further if there are runs for the instrument
266+
have_runs = bool(DataRun.objects.filter(instrument_id=instrument_id, created_on__gte=time_oldest).count() > 0)
267+
if have_runs:
268+
runs = run_rate(instrument_id, n_hours=n_hours)
269+
else:
270+
runs = __generate_empty_rates(n_hours)
271+
272+
# same for errors
273+
have_errors = bool(
274+
Error.objects.filter(
275+
run_status_id__run_id__instrument_id=instrument_id, run_status_id__created_on__gte=time_oldest
276+
).count()
277+
> 0
278+
)
279+
if have_errors:
280+
errors = error_rate(instrument_id, n_hours=n_hours)
281+
else:
282+
errors = __generate_empty_rates(n_hours)
283+
284+
# cache the run rate
254285
cache.set("%s_run_rate" % instrument_id.name, runs, settings.RUN_RATE_CACHE_TIMEOUT)
255286
cache.set(
256287
"%s_error_rate" % instrument_id.name,
257288
errors,
258289
settings.RUN_RATE_CACHE_TIMEOUT,
259290
)
291+
292+
# add the last run view for this instrument to the cache
260293
cache.set("%s_rate_last_run" % instrument_id.name, last_run)
261294

262295
return runs, errors

0 commit comments

Comments
 (0)