weight_rule.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #
  2. # Licensed to the Apache Software Foundation (ASF) under one
  3. # or more contributor license agreements. See the NOTICE file
  4. # distributed with this work for additional information
  5. # regarding copyright ownership. The ASF licenses this file
  6. # to you under the Apache License, Version 2.0 (the
  7. # "License"); you may not use this file except in compliance
  8. # with the License. You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing,
  13. # software distributed under the License is distributed on an
  14. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. # KIND, either express or implied. See the License for the
  16. # specific language governing permissions and limitations
  17. # under the License.
  18. from __future__ import annotations
  19. from enum import Enum
  20. import methodtools
  21. # Databases do not support arbitrary precision integers, so we need to limit the range of priority weights.
  22. # postgres: -2147483648 to +2147483647 (see https://www.postgresql.org/docs/current/datatype-numeric.html)
  23. # mysql: -2147483648 to +2147483647 (see https://dev.mysql.com/doc/refman/8.4/en/integer-types.html)
  24. # sqlite: -9223372036854775808 to +9223372036854775807 (see https://sqlite.org/datatype3.html)
  25. DB_SAFE_MINIMUM = -2147483648
  26. DB_SAFE_MAXIMUM = 2147483647
  27. def db_safe_priority(priority_weight: int) -> int:
  28. """Convert priority weight to a safe value for the database."""
  29. return max(DB_SAFE_MINIMUM, min(DB_SAFE_MAXIMUM, priority_weight))
  30. class WeightRule(str, Enum):
  31. """Weight rules."""
  32. DOWNSTREAM = "downstream"
  33. UPSTREAM = "upstream"
  34. ABSOLUTE = "absolute"
  35. @classmethod
  36. def is_valid(cls, weight_rule: str) -> bool:
  37. """Check if weight rule is valid."""
  38. return weight_rule in cls.all_weight_rules()
  39. @methodtools.lru_cache(maxsize=None)
  40. @classmethod
  41. def all_weight_rules(cls) -> set[str]:
  42. """Return all weight rules."""
  43. return set(cls.__members__.values())
  44. def __str__(self) -> str:
  45. return self.value