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