-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
68 lines (56 loc) · 2.6 KB
/
handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Copyright © 2018 Charles Corbett <nafredy@gmail.com>
//
package service
import (
"context"
"log"
)
// SayName generates a response to a Name request
func (s *Server) SayName(ctx context.Context, in *NodeMessage) (*NodeMessage, error) {
log.Printf("Name request received from %s, checking against my phonebook...\n", in.Name)
// Naively maintaining a cache of Nodes
err := s.AddNodeToPool(in)
if err != nil {
log.Printf("Something serious went wrong! %v", err)
}
log.Printf("[%s@%s:%d] Added. Responding....\n", in.Name, in.Host, in.Port)
return &NodeMessage{Name: s.Name, Host: s.Host, Port: int32(s.Port)}, nil
}
// SendWhisper receives and processes a sent whisper and may respond with a receipt
func (s *Server) SendWhisper(ctx context.Context, in *WhisperMessage) (*WhisperAck, error) {
log.Printf("Receive message from [%s]: %s\n", in.Source, in.Body)
return &WhisperAck{Response: true}, nil
}
// InformNode informs the target node of who it is, and retrieves the others identity
func (s *Server) InformNode(ctx context.Context, in *NodeInformMessage) (*NodeInformMessage, error) {
log.Printf("Received phonebook from [%s@%s:%d], processing...\n", in.Informer.Name, in.Informer.Host, in.Informer.Port)
for _, poolNode := range in.Pool {
err := s.AddNodeToPool(poolNode)
if err != nil {
// I haven't fully thought out how to inform the informer of this
log.Printf("Something serious went wrong! %v", err)
continue
}
}
informPool := s.BuildInformPool(in.Informer.Name, int(in.Informer.Port))
log.Printf("Acknowledging receipt & attempted incorporation.\n")
return informPool, nil
}
// RequestNode responds to a request to check our pool for a specific node
func (s *Server) RequestNode(ctx context.Context, in *NodeRequestMessage) (*NodeRequestReply, error) {
log.Printf("Received a request from [%s@%s:%d] to look up [%s@??:??], processing...", in.Informer.Name, in.Informer.Host, in.Informer.Port, in.Request)
if _, found := s.CheckPoolForNodeByName(in.Request); !found {
in.Exclude = append(in.Exclude, s.Me.Name)
err := s.AskPeersForNode(in.Request, in.Exclude)
if err != nil {
log.Printf("Something went wrong searching my graph.\n")
}
}
node, found := s.CheckPoolForNodeByName(in.Request)
if found {
log.Printf("Found [%s] for [%s@%s:%d], responding...", node.Name, in.Informer.Name, in.Informer.Host, in.Informer.Port)
return &NodeRequestReply{Found: true, Contents: node}, nil
}
log.Printf("I couldn't find [%s] for [%s@%s:%d], responding...", in.Request, in.Informer.Name, in.Informer.Host, in.Informer.Port)
return &NodeRequestReply{Found: false, Contents: &NodeMessage{}}, nil
}