experimental_features.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # Copyright 2023 The Matrix.org Foundation C.I.C
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from typing import TYPE_CHECKING, Dict
  15. from synapse.storage.database import DatabasePool, LoggingDatabaseConnection
  16. from synapse.storage.databases.main import CacheInvalidationWorkerStore
  17. from synapse.types import StrCollection
  18. from synapse.util.caches.descriptors import cached
  19. if TYPE_CHECKING:
  20. from synapse.rest.admin.experimental_features import ExperimentalFeature
  21. from synapse.server import HomeServer
  22. class ExperimentalFeaturesStore(CacheInvalidationWorkerStore):
  23. def __init__(
  24. self,
  25. database: DatabasePool,
  26. db_conn: LoggingDatabaseConnection,
  27. hs: "HomeServer",
  28. ) -> None:
  29. super().__init__(database, db_conn, hs)
  30. @cached()
  31. async def list_enabled_features(self, user_id: str) -> StrCollection:
  32. """
  33. Checks to see what features are enabled for a given user
  34. Args:
  35. user:
  36. the user to be queried on
  37. Returns:
  38. the features currently enabled for the user
  39. """
  40. enabled = await self.db_pool.simple_select_list(
  41. "per_user_experimental_features",
  42. {"user_id": user_id, "enabled": True},
  43. ["feature"],
  44. )
  45. return [feature["feature"] for feature in enabled]
  46. async def set_features_for_user(
  47. self,
  48. user: str,
  49. features: Dict["ExperimentalFeature", bool],
  50. ) -> None:
  51. """
  52. Enables or disables features for a given user
  53. Args:
  54. user:
  55. the user for whom to enable/disable the features
  56. features:
  57. pairs of features and True/False for whether the feature should be enabled
  58. """
  59. for feature, enabled in features.items():
  60. await self.db_pool.simple_upsert(
  61. table="per_user_experimental_features",
  62. keyvalues={"feature": feature, "user_id": user},
  63. values={"enabled": enabled},
  64. insertion_values={"user_id": user, "feature": feature},
  65. )
  66. await self.invalidate_cache_and_stream("list_enabled_features", (user,))