pool.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright 2016 Google Inc. All Rights Reserved.
  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 internal
  15. import (
  16. "errors"
  17. "google.golang.org/grpc/naming"
  18. )
  19. // PoolResolver provides a fixed list of addresses to load balance between
  20. // and does not provide further updates.
  21. type PoolResolver struct {
  22. poolSize int
  23. dialOpt *DialSettings
  24. ch chan []*naming.Update
  25. }
  26. // NewPoolResolver returns a PoolResolver
  27. // This is an EXPERIMENTAL API and may be changed or removed in the future.
  28. func NewPoolResolver(size int, o *DialSettings) *PoolResolver {
  29. return &PoolResolver{poolSize: size, dialOpt: o}
  30. }
  31. // Resolve returns a Watcher for the endpoint defined by the DialSettings
  32. // provided to NewPoolResolver.
  33. func (r *PoolResolver) Resolve(target string) (naming.Watcher, error) {
  34. if r.dialOpt.Endpoint == "" {
  35. return nil, errors.New("No endpoint configured")
  36. }
  37. addrs := make([]*naming.Update, 0, r.poolSize)
  38. for i := 0; i < r.poolSize; i++ {
  39. addrs = append(addrs, &naming.Update{Op: naming.Add, Addr: r.dialOpt.Endpoint, Metadata: i})
  40. }
  41. r.ch = make(chan []*naming.Update, 1)
  42. r.ch <- addrs
  43. return r, nil
  44. }
  45. // Next returns a static list of updates on the first call,
  46. // and blocks indefinitely until Close is called on subsequent calls.
  47. func (r *PoolResolver) Next() ([]*naming.Update, error) {
  48. return <-r.ch, nil
  49. }
  50. func (r *PoolResolver) Close() {
  51. close(r.ch)
  52. }