2022-06-03 08:09:47 -06:00
|
|
|
import time
|
|
|
|
|
from datetime import timedelta
|
|
|
|
|
|
|
|
|
|
from rest_framework import exceptions, serializers
|
|
|
|
|
|
|
|
|
|
from apps.base.models import UserNotificationPolicy
|
|
|
|
|
from apps.base.models.user_notification_policy import NotificationChannelPublicAPIOptions
|
|
|
|
|
from common.api_helpers.custom_fields import UserIdField
|
|
|
|
|
from common.api_helpers.exceptions import BadRequest
|
|
|
|
|
from common.api_helpers.mixins import EagerLoadingMixin
|
2023-07-18 18:17:53 +01:00
|
|
|
from common.ordered_model.serializer import OrderedModelSerializer
|
2022-06-03 08:09:47 -06:00
|
|
|
|
|
|
|
|
|
2023-07-18 18:17:53 +01:00
|
|
|
class PersonalNotificationRuleSerializer(EagerLoadingMixin, OrderedModelSerializer):
|
2022-06-03 08:09:47 -06:00
|
|
|
id = serializers.CharField(read_only=True, source="public_primary_key")
|
|
|
|
|
user_id = UserIdField(required=True, source="user")
|
|
|
|
|
type = serializers.CharField(
|
|
|
|
|
required=False,
|
|
|
|
|
)
|
|
|
|
|
duration = serializers.ChoiceField(
|
|
|
|
|
required=False, source="wait_delay", choices=UserNotificationPolicy.DURATION_CHOICES
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
SELECT_RELATED = ["user"]
|
|
|
|
|
|
|
|
|
|
# Public API has fields "step" and "notify_by" combined into one step "type"
|
|
|
|
|
# Step.NOTIFY is handled using NotificationChannelPublicAPIOptions class, but Step.WAIT is handled differently.
|
|
|
|
|
TYPE_WAIT = "wait"
|
|
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
|
model = UserNotificationPolicy
|
2023-07-18 18:17:53 +01:00
|
|
|
fields = OrderedModelSerializer.Meta.fields + ["id", "user_id", "type", "duration", "important"]
|
2022-06-03 08:09:47 -06:00
|
|
|
|
|
|
|
|
def create(self, validated_data):
|
|
|
|
|
if "type" not in validated_data:
|
|
|
|
|
raise exceptions.ValidationError({"type": "Type is required"})
|
|
|
|
|
|
|
|
|
|
validated_data = self.correct_validated_data(validated_data)
|
|
|
|
|
# type is alias for combined step + notify_by field in serializer
|
|
|
|
|
# correct_validated_data parse type to step + notify_by
|
|
|
|
|
# that is why step key is used instead of type below
|
|
|
|
|
if "wait_delay" in validated_data and validated_data["step"] != UserNotificationPolicy.Step.WAIT:
|
|
|
|
|
raise exceptions.ValidationError({"duration": "Duration can't be set"})
|
Fix duplicate orders for user notification policies (#2278)
# What this PR does
Fixes an issue when multiple user notification policies have duplicated
order values, leading to the following unexpected behaviours:
1. Not possible to rearrange notification policies that have duplicated
orders.
2. The notification system only executes the first policy from each
order group. For example, if there are policies with orders `[0, 0, 0,
0]`, only the first policy will be executed, and all others will be
skipped. So the user will see four policies in the UI, while only one of
them will be actually executed.
This PR fixes the issue by adding a unique index on `(user_id,
important, order)` for `UserNotificationPolicy` model. However, it's not
possible to add that unique index using the ordering library that we use
due to it's implementation details.
I added a new abstract Django model `OrderedModel` that's able to work
with such unique indices + under concurrent load.
Important info on this new `OrderedModel` abstract model:
- Orders are unique on the DB level
- Orders are allowed to be non-consecutive, for example order sequence
`[100, 150, 400]` is valid
- When deleting an instance, orders of other instances don't change.
This is a notable difference from the library we use. I think it's
better to only delete the instance without changing any other orders,
because it reduces the number of dependencies between instances (e.g.
Terraform drift will be much smaller this way if a policy is deleted via
the web UI).
## Which issue(s) this PR fixes
Related to https://github.com/grafana/oncall-private/issues/1680
## Checklist
- [x] Unit, integration, and e2e (if applicable) tests updated
- [x] Documentation added (or `pr:no public docs` PR label added if not
required)
- [x] `CHANGELOG.md` updated (or `pr:no changelog` PR label added if not
required)
2023-06-21 12:13:56 +01:00
|
|
|
|
2023-07-18 18:17:53 +01:00
|
|
|
return super().create(validated_data)
|
2022-06-03 08:09:47 -06:00
|
|
|
|
|
|
|
|
def to_internal_value(self, data):
|
|
|
|
|
if "duration" in data:
|
|
|
|
|
try:
|
|
|
|
|
time.strptime(data["duration"], "%H:%M:%S")
|
|
|
|
|
except (ValueError, TypeError):
|
|
|
|
|
try:
|
|
|
|
|
data["duration"] = str(timedelta(seconds=data["duration"]))
|
|
|
|
|
except (ValueError, TypeError):
|
|
|
|
|
raise BadRequest(detail="Invalid duration format")
|
|
|
|
|
return super().to_internal_value(data)
|
|
|
|
|
|
|
|
|
|
def to_representation(self, instance):
|
|
|
|
|
step = instance.step
|
|
|
|
|
result = super().to_representation(instance)
|
|
|
|
|
|
|
|
|
|
if instance.step == UserNotificationPolicy.Step.WAIT:
|
|
|
|
|
result["type"] = self.TYPE_WAIT
|
|
|
|
|
else:
|
|
|
|
|
result["type"] = NotificationChannelPublicAPIOptions.LABELS[instance.notify_by]
|
|
|
|
|
|
|
|
|
|
result = self.clear_fields(step, result)
|
|
|
|
|
|
|
|
|
|
if "duration" in result and result["duration"] is not None:
|
|
|
|
|
result["duration"] = result["duration"].seconds
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
# remove duration from response if step is not wait
|
|
|
|
|
def clear_fields(self, step, result):
|
|
|
|
|
possible_fields = ["duration"]
|
|
|
|
|
if step == UserNotificationPolicy.Step.WAIT:
|
|
|
|
|
possible_fields.remove("duration")
|
|
|
|
|
for field in possible_fields:
|
|
|
|
|
result.pop(field, None)
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
def correct_validated_data(self, validated_data):
|
|
|
|
|
rule_type = validated_data.get("type")
|
|
|
|
|
step, notification_channel = self._type_to_step_and_notification_channel(rule_type)
|
|
|
|
|
|
|
|
|
|
validated_data["step"] = step
|
|
|
|
|
|
|
|
|
|
if step == UserNotificationPolicy.Step.NOTIFY:
|
|
|
|
|
validated_data["notify_by"] = notification_channel
|
|
|
|
|
|
|
|
|
|
if step == UserNotificationPolicy.Step.WAIT and "wait_delay" not in validated_data:
|
|
|
|
|
validated_data["wait_delay"] = UserNotificationPolicy.FIVE_MINUTES
|
|
|
|
|
|
|
|
|
|
validated_data.pop("type")
|
|
|
|
|
return validated_data
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def _type_to_step_and_notification_channel(cls, rule_type):
|
|
|
|
|
if rule_type == cls.TYPE_WAIT:
|
|
|
|
|
return UserNotificationPolicy.Step.WAIT, None
|
|
|
|
|
|
|
|
|
|
for notification_channel in NotificationChannelPublicAPIOptions.AVAILABLE_FOR_USE:
|
|
|
|
|
label = NotificationChannelPublicAPIOptions.LABELS[notification_channel]
|
|
|
|
|
|
|
|
|
|
if rule_type == label:
|
|
|
|
|
return UserNotificationPolicy.Step.NOTIFY, notification_channel
|
|
|
|
|
|
|
|
|
|
raise exceptions.ValidationError({"type": "Invalid type"})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class PersonalNotificationRuleUpdateSerializer(PersonalNotificationRuleSerializer):
|
|
|
|
|
user_id = UserIdField(read_only=True, source="user")
|
|
|
|
|
important = serializers.BooleanField(read_only=True)
|
|
|
|
|
|
|
|
|
|
def update(self, instance, validated_data):
|
|
|
|
|
if validated_data.get("type", None):
|
|
|
|
|
validated_data = self.correct_validated_data(validated_data)
|
|
|
|
|
# type is alias for combined step + notify_by field in serializer
|
|
|
|
|
# correct_validated_data parse type to step + notify_by
|
|
|
|
|
# that is why step key is used instead of type below
|
|
|
|
|
if "wait_delay" in validated_data and validated_data["step"] != UserNotificationPolicy.Step.WAIT:
|
|
|
|
|
raise exceptions.ValidationError({"duration": "Duration can't be set"})
|
|
|
|
|
if validated_data["step"] != UserNotificationPolicy.Step.WAIT:
|
|
|
|
|
validated_data["wait_delay"] = None
|
|
|
|
|
else:
|
|
|
|
|
if "wait_delay" in validated_data and instance.step != UserNotificationPolicy.Step.WAIT:
|
|
|
|
|
raise exceptions.ValidationError({"duration": "Duration can't be set"})
|
|
|
|
|
|
|
|
|
|
return super().update(instance, validated_data)
|