Skip to content
Snippets Groups Projects
Commit 0a87700f authored by Philipp Schmidt's avatar Philipp Schmidt
Browse files

Add ExpiringEvents to count number events within a type window

parent 3a6c64da
No related branches found
No related tags found
1 merge request!1134[job_monitor] Watch and warn of jobs failing (almost) instantly by host
import pytest
import time
from webservice.job_monitor import ExpiringEvents
def test_expiring_events():
ev = ExpiringEvents(600)
assert ev.add() == 1
assert ev.add() == 2
assert ev.add(time.monotonic() - 800) == 2
assert ev.add() == 3
assert len(ev) == 3
......@@ -7,6 +7,8 @@ import os.path
import shlex
import signal
import time
from bisect import insort_left
from collections import deque
from datetime import datetime, timezone
from pathlib import Path
from subprocess import run, PIPE
......@@ -38,6 +40,33 @@ STATE_ABBREVS = {
}
class ExpiringEvents:
"""Track events occuring within a time window.
Args:
window (int, optional): Time window in seconds, 600 by default.
"""
def __init__(self, window=600):
self.window = window
self.events = deque()
def add(self, event=None):
now = time.monotonic()
insort_left(self.events, event or now)
cutoff = now - self.window
while self.events and self.events[0] < cutoff:
self.events.popleft()
return len(self.events)
def __len__(self):
return len(self.events)
class NoOpProducer:
"""Fills in for Kafka producer object when setting that up fails"""
def send(self, topic, value):
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment