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	pb "github.com/golang/groupcache/groupcachepb"
23)
24
25// Context is an opaque value passed through calls to the
26// ProtoGetter. It may be nil if your ProtoGetter implementation does
27// not require a context.
28type Context interface{}
29
30// ProtoGetter is the interface that must be implemented by a peer.
31type ProtoGetter interface {
32	Get(context Context, in *pb.GetRequest, out *pb.GetResponse) error
33}
34
35// PeerPicker is the interface that must be implemented to locate
36// the peer that owns a specific key.
37type PeerPicker interface {
38	// PickPeer returns the peer that owns the specific key
39	// and true to indicate that a remote peer was nominated.
40	// It returns nil, false if the key owner is the current peer.
41	PickPeer(key string) (peer ProtoGetter, ok bool)
42}
43
44// NoPeers is an implementation of PeerPicker that never finds a peer.
45type NoPeers struct{}
46
47func (NoPeers) PickPeer(key string) (peer ProtoGetter, ok bool) { return }
48
49var (
50	portPicker func(groupName string) PeerPicker
51)
52
53// RegisterPeerPicker registers the peer initialization function.
54// It is called once, when the first group is created.
55// Either RegisterPeerPicker or RegisterPerGroupPeerPicker should be
56// called exactly once, but not both.
57func RegisterPeerPicker(fn func() PeerPicker) {
58	if portPicker != nil {
59		panic("RegisterPeerPicker called more than once")
60	}
61	portPicker = func(_ string) PeerPicker { return fn() }
62}
63
64// RegisterPerGroupPeerPicker registers the peer initialization function,
65// which takes the groupName, to be used in choosing a PeerPicker.
66// It is called once, when the first group is created.
67// Either RegisterPeerPicker or RegisterPerGroupPeerPicker should be
68// called exactly once, but not both.
69func RegisterPerGroupPeerPicker(fn func(groupName string) PeerPicker) {
70	if portPicker != nil {
71		panic("RegisterPeerPicker called more than once")
72	}
73	portPicker = fn
74}
75
76func getPeers(groupName string) PeerPicker {
77	if portPicker == nil {
78		return NoPeers{}
79	}
80	pk := portPicker(groupName)
81	if pk == nil {
82		pk = NoPeers{}
83	}
84	return pk
85}
86