-
Notifications
You must be signed in to change notification settings - Fork 0
/
keepAlive_pubsub.go
59 lines (52 loc) · 1.75 KB
/
keepAlive_pubsub.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
package node
import (
"context"
"time"
ipfsLog "github.com/ipfs/go-log/v2"
pubsub "github.com/libp2p/go-libp2p-pubsub"
"github.com/libp2p/go-libp2p/core/host"
"github.com/pierreleocadie/SecuraChain/internal/config"
"github.com/pierreleocadie/SecuraChain/internal/network"
)
func PubsubKeepRelayConnectionAlive(ctx context.Context,
ps *pubsub.PubSub, cfg *config.Config,
log *ipfsLog.ZapEventLogger, host host.Host) {
// Run KeepRelayConnectionAlive only if its behind a NAT
if !network.NATDiscovery(log) {
return
}
// KeepRelayConnectionAlive
keepRelayConnectionAliveTopic, err := ps.Join(cfg.KeepRelayConnectionAliveStringFlag)
if err != nil {
log.Warnf("Failed to join KeepRelayConnectionAlive topic: %s", err)
}
// Subscribe to KeepRelayConnectionAlive topic
subKeepRelayConnectionAlive, err := keepRelayConnectionAliveTopic.Subscribe()
if err != nil {
log.Warnf("Failed to subscribe to KeepRelayConnectionAlive topic: %s", err)
}
// Handle incoming KeepRelayConnectionAlive messages
go func() {
for {
msg, err := subKeepRelayConnectionAlive.Next(ctx)
if err != nil {
log.Errorf("Failed to get next message from KeepRelayConnectionAlive topic: %s", err)
continue
}
log.Debugf("Received KeepRelayConnectionAlive message from %s", msg.GetFrom().String())
log.Debugf("KeepRelayConnectionAlive: %s", string(msg.Data))
}
}()
// Handle outgoing KeepRelayConnectionAlive messages
go func() {
for {
time.Sleep(cfg.KeepRelayConnectionAliveInterval)
err := keepRelayConnectionAliveTopic.Publish(ctx, network.GeneratePacket(host.ID()))
if err != nil {
log.Errorf("Failed to publish KeepRelayConnectionAlive message: %s", err)
continue
}
log.Debugf("KeepRelayConnectionAlive message sent successfully")
}
}()
}