Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bug] Add a handler to unexpected json file format #904

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 19 additions & 17 deletions piperider_cli/event/collector.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
import platform
import sys
import time
from contextlib import contextmanager
from datetime import datetime
from json import JSONDecodeError

import portalocker
import requests
Expand Down Expand Up @@ -64,7 +66,6 @@
app_version=__version__,
)

# TODO: handle exception when writing to file
self._store_to_file(event)
if self._is_full():
self.send_events()
Expand All @@ -83,45 +84,46 @@
o = json.loads(f.read())
return len(o.get('unsend_events', [])) >= self._upload_threshold

def send_events(self):
@contextmanager
def load_json(self):
with portalocker.Lock(self._unsend_events_file, 'r+', timeout=5) as f:
o = json.loads(f.read())
try:
o = json.loads(f.read())
yield o
except JSONDecodeError:
o = dict(unsend_events=[])
yield o

Check warning on line 95 in piperider_cli/event/collector.py

View check run for this annotation

Codecov / codecov/patch

piperider_cli/event/collector.py#L93-L95

Added lines #L93 - L95 were not covered by tests
finally:
f.seek(0)
f.truncate()
f.write(json.dumps(o))

def send_events(self):
with self.load_json() as o:
payload = dict(
api_key=self._api_key,
events=o['unsend_events'],
)
o['unsend_events'] = []
f.seek(0)
f.truncate()
f.write(json.dumps(o))
try:
requests.post(self._api_endpoint, json=payload)
except Exception:
# TODO: handle exception when sending events
pass

def _store_to_file(self, event):
with portalocker.Lock(self._unsend_events_file, 'r+', timeout=5) as f:
o = json.loads(f.read())
with self.load_json() as o:
events = o.get('unsend_events', None)
if events is None:
o['unsend_events'] = []

o['unsend_events'].append(event)
f.seek(0)
f.truncate()
f.write(json.dumps(o))

def _cleanup_unsend_events(self):
with portalocker.Lock(self._unsend_events_file, 'r+', timeout=5) as f:
o = json.loads(f.read())
with self.load_json() as o:
events = o.get('unsend_events', None)
if events is None:
o['unsend_events'] = []

while len(o['unsend_events']) > self._delete_threshold:
o['unsend_events'].pop(0)

f.seek(0)
f.truncate()
f.write(json.dumps(o))
Loading