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

Using dedicated event to store working time #7958

Merged
merged 42 commits into from
Jun 3, 2024
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
3bf992a
Using dedicated event to store working time
bsekachev May 28, 2024
f36cf4e
Some code refactoring
bsekachev May 28, 2024
22e0e1d
Fixed minor issues
bsekachev May 29, 2024
ae9ac55
Applied suggestion
bsekachev May 29, 2024
267b492
Do not allow working time events from client
bsekachev May 29, 2024
d896092
Tmp
bsekachev May 29, 2024
2b8bc1c
Aborted extra changes
bsekachev May 29, 2024
9bbd829
Dedicated place to handle working time events
bsekachev May 29, 2024
4d84047
Working time logic removed from serializer
bsekachev May 29, 2024
18f01c7
Removed unused import
bsekachev May 29, 2024
d41b14f
Avoid passing server events from client
bsekachev May 29, 2024
0361fd0
Merge branch 'develop' into bs/dedicated_event_for_wt
bsekachev May 29, 2024
5cf3e8d
Added documentation
bsekachev May 29, 2024
5eeab68
Fixed remark
bsekachev May 29, 2024
6d0ede0
Task/project from event
bsekachev May 29, 2024
da2afb1
Refactoring
bsekachev May 29, 2024
5b0363c
Reduced complexity
bsekachev May 29, 2024
3d1f4dd
Added couple of typings
bsekachev May 29, 2024
d1f5faf
Documented one more clarification
bsekachev May 29, 2024
afedb2a
Minor refactoring
bsekachev May 29, 2024
803a0d4
Updated imports
bsekachev May 29, 2024
5e149be
Added changelog fragment
bsekachev May 29, 2024
6436916
Use validation error
bsekachev May 29, 2024
71ace7f
Fixed timestamp
bsekachev May 29, 2024
8c99764
Allow blank email
bsekachev May 29, 2024
c7ea9a3
Updated schema
bsekachev May 29, 2024
a43b060
Reworked last change
bsekachev May 29, 2024
9e5e6db
Fixed event payload
bsekachev May 29, 2024
a53b5f3
Fixed serializer
bsekachev May 29, 2024
32604a1
Isort
bsekachev May 29, 2024
6684af7
Moved line
bsekachev May 29, 2024
5ca91b3
Missing project id in load:job event
bsekachev May 30, 2024
9b4f7a0
Applied comments
bsekachev May 30, 2024
054afff
Applied comments
bsekachev May 30, 2024
452cef5
Fixed linter
bsekachev May 30, 2024
c5f201d
Added indent
bsekachev May 30, 2024
d8a1fd5
Remark
bsekachev May 30, 2024
01e37a4
Fixed exception format and tests
bsekachev May 30, 2024
4179a29
Merge branch 'develop' into bs/dedicated_event_for_wt
bsekachev May 31, 2024
3d3b9ac
Applied comment
bsekachev May 31, 2024
24eb5fe
Applied comments
bsekachev Jun 3, 2024
d6080ee
Merge branch 'develop' into bs/dedicated_event_for_wt
bsekachev Jun 3, 2024
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
71 changes: 64 additions & 7 deletions cvat/apps/events/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
import datetime
import json

from contextlib import suppress
from rest_framework import serializers
from cvat.apps.engine.models import Job

class EventSerializer(serializers.Serializer):
scope = serializers.CharField(required=True)
Expand All @@ -30,10 +32,43 @@ class ClientEventsSerializer(serializers.Serializer):
events = EventSerializer(many=True, default=[])
previous_event = EventSerializer(default=None, allow_null=True, write_only=True)
timestamp = serializers.DateTimeField()
_WORKING_TIME_SCOPE = 'send:working_time'
_TIME_THRESHOLD = datetime.timedelta(seconds=100)
_WORKING_TIME_RESOLUTION = datetime.timedelta(milliseconds=1)
_COLLAPSED_EVENT_SCOPES = frozenset(("change:frame",))

@classmethod
def _generate_wt_event(cls, job_id: int | None, wt: datetime.timedelta, common: dict) -> EventSerializer | None:
if wt.total_seconds():
task_id = None
project_id = None

if job_id is not None:
with suppress(Job.DoesNotExist):
task_id, project_id = Job.objects.values_list(
"segment__task__id", "segment__task__project__id"
).get(pk=job_id)

value = wt // cls._WORKING_TIME_RESOLUTION
event = EventSerializer(data={
**common,
"scope": cls._WORKING_TIME_SCOPE,
"obj_name": "working_time",
"obj_val": value,
"source": "server",
"count": 1,
"project_id": project_id,
"task_id": task_id,
"job_id": job_id,
# keep it in payload for backward compatibility
# but in the future it is much better to use a dedicated field "obj_value"
# because parsing JSON in SQL query is very slow
"payload": json.dumps({ "working_time": value })
})

event.is_valid(raise_exception=True)
return event

@classmethod
def _end_timestamp(cls, event: dict) -> datetime.datetime:
if event["scope"] in cls._COLLAPSED_EVENT_SCOPES:
Expand All @@ -54,10 +89,14 @@ def to_internal_value(self, data):

if previous_event := data["previous_event"]:
previous_end_timestamp = self._end_timestamp(previous_event)
previous_job_id = previous_event.get("job_id")
elif data["events"]:
previous_end_timestamp = data["events"][0]["timestamp"]
previous_job_id = data["events"][0].get("job_id")

working_time_per_job = {}
for event in data["events"]:
job_id = event.get('job_id')
working_time = datetime.timedelta()

timestamp = event["timestamp"]
Expand All @@ -73,21 +112,39 @@ def to_internal_value(self, data):
working_time += end_timestamp - previous_end_timestamp
previous_end_timestamp = end_timestamp

payload = json.loads(event.get("payload", "{}"))
payload.update({
"working_time": working_time // self._WORKING_TIME_RESOLUTION,
"username": request.user.username,
})
if previous_job_id not in working_time_per_job:
working_time_per_job[previous_job_id] = datetime.timedelta()
working_time_per_job[previous_job_id] += working_time
previous_job_id = job_id

try:
json_payload = json.loads(event.get("payload", "{}"))
bsekachev marked this conversation as resolved.
Show resolved Hide resolved
except json.JSONDecodeError:
raise serializers.ValidationError("JSON payload is not valid in passed event")

event.update({
"timestamp": str((timestamp + time_correction).timestamp()),
"timestamp": str(timestamp + time_correction),
"source": "client",
"org_id": org_id,
"org_slug": org_slug,
"user_id": request.user.id,
"user_name": request.user.username,
"user_email": request.user.email,
"payload": json.dumps(payload),
"payload": json.dumps(json_payload),
})

common = {
"timestamp": str(receive_time),
"user_id": request.user.id,
"user_name": request.user.username,
"user_email": request.user.email,
"org_id": org_id,
"org_slug": org_slug,
}

for job_id in working_time_per_job:
event = ClientEventsSerializer._generate_wt_event(job_id, working_time_per_job[job_id], common)
if event:
data["events"].append(event.validated_data)

return data
1 change: 1 addition & 0 deletions cvat/apps/events/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from django.conf import settings
from rest_framework import status, viewsets
from rest_framework.response import Response
from rest_framework.exceptions import PermissionDenied
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove unused import.

- from rest_framework.exceptions import PermissionDenied

This import statement for PermissionDenied is not used anywhere in the file. It should be removed to keep the code clean and efficient unless there are plans to use it in the near future.


Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
from rest_framework.exceptions import PermissionDenied

from drf_spectacular.utils import OpenApiResponse, OpenApiParameter, extend_schema
from drf_spectacular.types import OpenApiTypes
from rest_framework.renderers import JSONRenderer
Expand Down
Loading