-
Notifications
You must be signed in to change notification settings - Fork 35
/
state.go
101 lines (78 loc) · 2.14 KB
/
state.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// SPDX-License-Identifier: MIT
package server
import (
"context"
"encoding/json"
"time"
"github.com/ssb-ngi-pointer/go-ssb-room/internal/network"
"github.com/ssb-ngi-pointer/go-ssb-room/roomstate"
refs "go.mindeco.de/ssb-refs"
kitlog "github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"go.cryptoscope.co/muxrpc/v2"
)
type Handler struct {
logger kitlog.Logger
self refs.FeedRef
state *roomstate.Manager
}
func (h *Handler) isRoom(context.Context, *muxrpc.Request) (interface{}, error) {
level.Debug(h.logger).Log("called", "isRoom")
return true, nil
}
func (h *Handler) ping(context.Context, *muxrpc.Request) (interface{}, error) {
now := time.Now().UnixNano() / 1000
level.Debug(h.logger).Log("called", "ping")
return now, nil
}
func (h *Handler) announce(_ context.Context, req *muxrpc.Request) (interface{}, error) {
level.Debug(h.logger).Log("called", "announce")
ref, err := network.GetFeedRefFromAddr(req.RemoteAddr())
if err != nil {
return nil, err
}
h.state.AddEndpoint(*ref, req.Endpoint())
return false, nil
}
func (h *Handler) leave(_ context.Context, req *muxrpc.Request) (interface{}, error) {
ref, err := network.GetFeedRefFromAddr(req.RemoteAddr())
if err != nil {
return nil, err
}
h.state.Remove(*ref)
return false, nil
}
func (h *Handler) endpoints(_ context.Context, req *muxrpc.Request, snk *muxrpc.ByteSink) error {
level.Debug(h.logger).Log("called", "endpoints")
toPeer := newForwarder(snk)
// for future updates
h.state.Register(toPeer)
ref, err := network.GetFeedRefFromAddr(req.RemoteAddr())
if err != nil {
return err
}
has := h.state.AlreadyAdded(*ref, req.Endpoint())
if !has {
// just send the current state to the new peer
toPeer.Update(h.state.List())
}
return nil
}
type updateForwarder struct {
snk *muxrpc.ByteSink
enc *json.Encoder
}
func newForwarder(snk *muxrpc.ByteSink) updateForwarder {
enc := json.NewEncoder(snk)
snk.SetEncoding(muxrpc.TypeJSON)
return updateForwarder{
snk: snk,
enc: enc,
}
}
func (uf updateForwarder) Update(members []string) error {
return uf.enc.Encode(members)
}
func (uf updateForwarder) Close() error {
return uf.snk.Close()
}