ctx.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. // Copyright 2020 The etcd Authors
  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 clientv3
  15. import (
  16. "context"
  17. "go.etcd.io/etcd/api/v3/v3rpc/rpctypes"
  18. "go.etcd.io/etcd/api/v3/version"
  19. "google.golang.org/grpc/metadata"
  20. )
  21. // WithRequireLeader requires client requests to only succeed
  22. // when the cluster has a leader.
  23. func WithRequireLeader(ctx context.Context) context.Context {
  24. md, ok := metadata.FromOutgoingContext(ctx)
  25. if !ok { // no outgoing metadata ctx key, create one
  26. md = metadata.Pairs(rpctypes.MetadataRequireLeaderKey, rpctypes.MetadataHasLeader)
  27. return metadata.NewOutgoingContext(ctx, md)
  28. }
  29. copied := md.Copy() // avoid racey updates
  30. // overwrite/add 'hasleader' key/value
  31. copied.Set(rpctypes.MetadataRequireLeaderKey, rpctypes.MetadataHasLeader)
  32. return metadata.NewOutgoingContext(ctx, copied)
  33. }
  34. // embeds client version
  35. func withVersion(ctx context.Context) context.Context {
  36. md, ok := metadata.FromOutgoingContext(ctx)
  37. if !ok { // no outgoing metadata ctx key, create one
  38. md = metadata.Pairs(rpctypes.MetadataClientAPIVersionKey, version.APIVersion)
  39. return metadata.NewOutgoingContext(ctx, md)
  40. }
  41. copied := md.Copy() // avoid racey updates
  42. // overwrite/add version key/value
  43. copied.Set(rpctypes.MetadataClientAPIVersionKey, version.APIVersion)
  44. return metadata.NewOutgoingContext(ctx, copied)
  45. }