Skip to content
File

Blob: tun/server/resolve.go

go86 lines
1package server
2 
3import (
4 "context"
5 "fmt"
6 
7 "go.miragespace.co/specter/spec/protocol"
8 "go.miragespace.co/specter/spec/tun"
9 
10 "github.com/avast/retry-go/v5"
11 "go.uber.org/zap"
12)
13 
14func (s *Server) publishDestinations(ctx context.Context) error {
15 destinations := &protocol.TunnelDestination{
16 Chord: s.ChordTransport.Identity(),
17 Tunnel: s.TunnelTransport.Identity(),
18 }
19 
20 buf, err := destinations.MarshalVT()
21 if err != nil {
22 return err
23 }
24 
25 keys := []string{
26 tun.DestinationByChordKey(s.ChordTransport.Identity()),
27 tun.DestinationByTunnelKey(s.TunnelTransport.Identity()),
28 }
29 
30 retrier := retry.New(
31 retry.Context(ctx),
32 retry.Attempts(3),
33 retry.LastErrorOnly(true),
34 )
35 for _, key := range keys {
36 // Repeating this fixed value is safe even if a previous write's response was lost.
37 err := retrier.Do(func() error {
38 return s.Chord.Put(ctx, []byte(key), buf)
39 })
40 if err != nil {
41 return err
42 }
43 }
44 
45 s.Logger.Info("Destinations published on chord",
46 zap.String("chord", keys[0]),
47 zap.String("tunnel", keys[1]),
48 )
49 
50 return nil
51}
52 
53func (s *Server) unpublishDestinations(ctx context.Context) {
54 keys := []string{
55 tun.DestinationByChordKey(s.ChordTransport.Identity()),
56 tun.DestinationByTunnelKey(s.TunnelTransport.Identity()),
57 }
58 
59 for _, key := range keys {
60 err := s.Chord.Delete(ctx, []byte(key))
61 if err != nil {
62 s.Logger.Error("Failed to unpublish destinations on chord", zap.Error(err))
63 return
64 }
65 }
66 
67 s.Logger.Info("Destination unpublished on chord",
68 zap.String("chord", keys[0]),
69 zap.String("tunnel", keys[1]))
70}
71 
72func (s *Server) lookupDestination(ctx context.Context, key string) (*protocol.TunnelDestination, error) {
73 buf, err := s.Chord.Get(ctx, []byte(key))
74 if err != nil {
75 return nil, err
76 }
77 if len(buf) == 0 {
78 return nil, fmt.Errorf("no destination found with key: %s", key)
79 }
80 dst := &protocol.TunnelDestination{}
81 if err := dst.UnmarshalVT(buf); err != nil {
82 return nil, fmt.Errorf("tunnel destination decode failure: %w", err)
83 }
84 return dst, nil
85}