StatisticsCache.java 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package com.provectus.kafka.ui.service;
  2. import com.provectus.kafka.ui.model.InternalPartitionsOffsets;
  3. import com.provectus.kafka.ui.model.KafkaCluster;
  4. import com.provectus.kafka.ui.model.ServerStatusDTO;
  5. import com.provectus.kafka.ui.model.Statistics;
  6. import java.util.HashMap;
  7. import java.util.List;
  8. import java.util.Map;
  9. import java.util.Objects;
  10. import java.util.concurrent.ConcurrentHashMap;
  11. import org.apache.kafka.clients.admin.ConfigEntry;
  12. import org.apache.kafka.clients.admin.TopicDescription;
  13. import org.springframework.stereotype.Component;
  14. @Component
  15. public class StatisticsCache {
  16. private final Map<String, Statistics> cache = new ConcurrentHashMap<>();
  17. public StatisticsCache(ClustersStorage clustersStorage) {
  18. var initializing = Statistics.empty().toBuilder().status(ServerStatusDTO.INITIALIZING).build();
  19. clustersStorage.getKafkaClusters().forEach(c -> cache.put(c.getName(), initializing));
  20. }
  21. public synchronized void replace(KafkaCluster c, Statistics stats) {
  22. cache.put(c.getName(), stats);
  23. }
  24. public synchronized void update(KafkaCluster c,
  25. Map<String, TopicDescription> descriptions,
  26. Map<String, List<ConfigEntry>> configs,
  27. InternalPartitionsOffsets partitionsOffsets) {
  28. var stats = get(c);
  29. replace(
  30. c,
  31. stats.toBuilder()
  32. .clusterState(stats.getClusterState().updateTopics(descriptions, configs, partitionsOffsets))
  33. .build()
  34. );
  35. }
  36. public synchronized void onTopicDelete(KafkaCluster c, String topic) {
  37. var stats = get(c);
  38. replace(
  39. c,
  40. stats.toBuilder()
  41. .clusterState(stats.getClusterState().topicDeleted(topic))
  42. .build()
  43. );
  44. }
  45. public Statistics get(KafkaCluster c) {
  46. return Objects.requireNonNull(cache.get(c.getName()), "Statistics for unknown cluster requested");
  47. }
  48. }