...

Source file src/go.etcd.io/etcd/client/v3/ctx.go

Documentation: go.etcd.io/etcd/client/v3

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

View as plain text