blob: 38cee6c27e4a094b0ed4fca15e3329e0e67d5640 [file] [log] [blame]
Naveen Sampath04696f72022-06-13 15:19:14 +05301// 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"
Naveen Sampath04696f72022-06-13 15:19:14 +053019
Naveen Sampath04696f72022-06-13 15:19:14 +053020 "google.golang.org/grpc/metadata"
Abhay Kumarfe505f22025-11-10 14:16:31 +000021
22 "go.etcd.io/etcd/api/v3/v3rpc/rpctypes"
23 "go.etcd.io/etcd/api/v3/version"
Naveen Sampath04696f72022-06-13 15:19:14 +053024)
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
Abhay Kumarfe505f22025-11-10 14:16:31 +000036 copied.Set(rpctypes.MetadataRequireLeaderKey, rpctypes.MetadataHasLeader)
Naveen Sampath04696f72022-06-13 15:19:14 +053037 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
Abhay Kumarfe505f22025-11-10 14:16:31 +000049 copied.Set(rpctypes.MetadataClientAPIVersionKey, version.APIVersion)
Naveen Sampath04696f72022-06-13 15:19:14 +053050 return metadata.NewOutgoingContext(ctx, copied)
51}