1/*
2Copyright 2012 Google Inc.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8     http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17// peers.go defines how processes find and communicate with their peers.
18
19package groupcache
20
21import (
22	"context"
23
24	pb "github.com/golang/groupcache/groupcachepb"
25)
26
27// ProtoGetter is the interface that must be implemented by a peer.
28type ProtoGetter interface {
29	Get(ctx context.Context, in *pb.GetRequest, out *pb.GetResponse) error
30}
31
32// PeerPicker is the interface that must be implemented to locate
33// the peer that owns a specific key.
34type PeerPicker interface {
35	// PickPeer returns the peer that owns the specific key
36	// and true to indicate that a remote peer was nominated.
37	// It returns nil, false if the key owner is the current peer.
38	PickPeer(key string) (peer ProtoGetter, ok bool)
39}
40
41// NoPeers is an implementation of PeerPicker that never finds a peer.
42type NoPeers struct{}
43
44func (NoPeers) PickPeer(key string) (peer ProtoGetter, ok bool) { return }
45
46var (
47	portPicker func(groupName string) PeerPicker
48)
49
50// RegisterPeerPicker registers the peer initialization function.
51// It is called once, when the first group is created.
52// Either RegisterPeerPicker or RegisterPerGroupPeerPicker should be
53// called exactly once, but not both.
54func RegisterPeerPicker(fn func() PeerPicker) {
55	if portPicker != nil {
56		panic("RegisterPeerPicker called more than once")
57	}
58	portPicker = func(_ string) PeerPicker { return fn() }
59}
60
61// RegisterPerGroupPeerPicker registers the peer initialization function,
62// which takes the groupName, to be used in choosing a PeerPicker.
63// It is called once, when the first group is created.
64// Either RegisterPeerPicker or RegisterPerGroupPeerPicker should be
65// called exactly once, but not both.
66func RegisterPerGroupPeerPicker(fn func(groupName string) PeerPicker) {
67	if portPicker != nil {
68		panic("RegisterPeerPicker called more than once")
69	}
70	portPicker = fn
71}
72
73func getPeers(groupName string) PeerPicker {
74	if portPicker == nil {
75		return NoPeers{}
76	}
77	pk := portPicker(groupName)
78	if pk == nil {
79		pk = NoPeers{}
80	}
81	return pk
82}
83