endpoints.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright (c) 2017 Uber Technologies, Inc.
  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. package rpcmetrics
  15. import "sync"
  16. // normalizedEndpoints is a cache for endpointName -> safeName mappings.
  17. type normalizedEndpoints struct {
  18. names map[string]string
  19. maxSize int
  20. defaultName string
  21. normalizer NameNormalizer
  22. mux sync.RWMutex
  23. }
  24. func newNormalizedEndpoints(maxSize int, normalizer NameNormalizer) *normalizedEndpoints {
  25. return &normalizedEndpoints{
  26. maxSize: maxSize,
  27. normalizer: normalizer,
  28. names: make(map[string]string, maxSize),
  29. }
  30. }
  31. // normalize looks up the name in the cache, if not found it uses normalizer
  32. // to convert the name to a safe name. If called with more than maxSize unique
  33. // names it returns "" for all other names beyond those already cached.
  34. func (n *normalizedEndpoints) normalize(name string) string {
  35. n.mux.RLock()
  36. norm, ok := n.names[name]
  37. l := len(n.names)
  38. n.mux.RUnlock()
  39. if ok {
  40. return norm
  41. }
  42. if l >= n.maxSize {
  43. return ""
  44. }
  45. return n.normalizeWithLock(name)
  46. }
  47. func (n *normalizedEndpoints) normalizeWithLock(name string) string {
  48. norm := n.normalizer.Normalize(name)
  49. n.mux.Lock()
  50. defer n.mux.Unlock()
  51. // cache may have grown while we were not holding the lock
  52. if len(n.names) >= n.maxSize {
  53. return ""
  54. }
  55. n.names[name] = norm
  56. return norm
  57. }