_slaved_id_tracker.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from typing import List, Optional, Tuple
  16. from synapse.storage.types import Connection
  17. from synapse.storage.util.id_generators import _load_current_id
  18. class SlavedIdTracker:
  19. def __init__(
  20. self,
  21. db_conn: Connection,
  22. table: str,
  23. column: str,
  24. extra_tables: Optional[List[Tuple[str, str]]] = None,
  25. step: int = 1,
  26. ):
  27. self.step = step
  28. self._current = _load_current_id(db_conn, table, column, step)
  29. if extra_tables:
  30. for table, column in extra_tables:
  31. self.advance(None, _load_current_id(db_conn, table, column))
  32. def advance(self, instance_name: Optional[str], new_id: int):
  33. self._current = (max if self.step > 0 else min)(self._current, new_id)
  34. def get_current_token(self) -> int:
  35. """
  36. Returns:
  37. int
  38. """
  39. return self._current
  40. def get_current_token_for_writer(self, instance_name: str) -> int:
  41. """Returns the position of the given writer.
  42. For streams with single writers this is equivalent to
  43. `get_current_token`.
  44. """
  45. return self.get_current_token()