Skip to content

Commit b314d09

Browse files
committed
notifications: add notification manager
This commit adds a generic notification manager that can be used to subscribe to different types of notifications.
1 parent 3a1ff95 commit b314d09

File tree

3 files changed

+409
-0
lines changed

3 files changed

+409
-0
lines changed

notifications/log.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package notifications
2+
3+
import (
4+
"github.com/btcsuite/btclog"
5+
"github.com/lightningnetwork/lnd/build"
6+
)
7+
8+
// Subsystem defines the sub system name of this package.
9+
const Subsystem = "NTFNS"
10+
11+
// log is a logger that is initialized with no output filters. This
12+
// means the package will not perform any logging by default until the caller
13+
// requests it.
14+
var log btclog.Logger
15+
16+
// The default amount of logging is none.
17+
func init() {
18+
UseLogger(build.NewSubLogger(Subsystem, nil))
19+
}
20+
21+
// UseLogger uses a specified Logger to output package logging info.
22+
// This should be used in preference to SetLogWriter if the caller is also
23+
// using btclog.
24+
func UseLogger(logger btclog.Logger) {
25+
log = logger
26+
}

notifications/manager.go

Lines changed: 222 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,222 @@
1+
package notifications
2+
3+
import (
4+
"context"
5+
"sync"
6+
"time"
7+
8+
"github.com/lightninglabs/loop/swapserverrpc"
9+
"google.golang.org/grpc"
10+
)
11+
12+
type NotificationType int
13+
14+
const (
15+
NotificationTypeUnknown NotificationType = iota
16+
NotificationTypeReservation
17+
)
18+
19+
type NotificationsClient interface {
20+
SubscribeNotifications(ctx context.Context,
21+
in *swapserverrpc.SubscribeNotificationsRequest,
22+
opts ...grpc.CallOption) (
23+
swapserverrpc.SwapServer_SubscribeNotificationsClient, error)
24+
}
25+
26+
// Config contains all the services that the notification manager needs to
27+
// operate.
28+
type Config struct {
29+
// Client is the client used to communicate with the swap server.
30+
Client NotificationsClient
31+
32+
// FetchL402 is the function used to fetch the l402 token.
33+
FetchL402 func(context.Context) error
34+
}
35+
36+
// Manager is a manager for notifications that the swap server sends to the
37+
// client.
38+
type Manager struct {
39+
cfg *Config
40+
41+
hasL402 bool
42+
43+
subscribers map[NotificationType][]subscriber
44+
sync.Mutex
45+
}
46+
47+
// NewManager creates a new notification manager.
48+
func NewManager(cfg *Config) *Manager {
49+
return &Manager{
50+
cfg: cfg,
51+
subscribers: make(map[NotificationType][]subscriber),
52+
}
53+
}
54+
55+
type subscriber struct {
56+
subCtx context.Context
57+
recvChan interface{}
58+
}
59+
60+
// SubscribeReservations subscribes to the reservation notifications.
61+
func (m *Manager) SubscribeReservations(ctx context.Context,
62+
) <-chan *swapserverrpc.ServerReservationNotification {
63+
64+
// We'll create a channel that we'll use to send the notifications to the
65+
// caller.
66+
notifChan := make(
67+
chan *swapserverrpc.ServerReservationNotification, //nolint:lll
68+
)
69+
sub := subscriber{
70+
subCtx: ctx,
71+
recvChan: notifChan,
72+
}
73+
74+
m.Lock()
75+
m.subscribers[NotificationTypeReservation] = append(
76+
m.subscribers[NotificationTypeReservation],
77+
sub,
78+
)
79+
m.Unlock()
80+
81+
return notifChan
82+
}
83+
84+
// Run starts the notification manager. It will keep on running until the
85+
// context is canceled. It will subscribe to notifications and forward them to
86+
// the subscribers. On a first successful connection to the server, it will
87+
// close the readyChan to signal that the manager is ready.
88+
func (n *Manager) Run(ctx context.Context, readyChan chan<- struct{}) error {
89+
// In order to create a valid l402 we first are going to call
90+
// the FetchL402 method. As a client might not have outbound capacity
91+
// yet, we'll retry until we get a valid response.
92+
if !n.hasL402 {
93+
n.fetchL402(ctx)
94+
}
95+
96+
var closedChan bool
97+
98+
// Initially we want to immediately try to connect to the server.
99+
waitTime := time.Duration(0)
100+
101+
// Start the notification runloop.
102+
for {
103+
timer := time.NewTimer(waitTime)
104+
// Increase the wait time for the next iteration.
105+
waitTime += time.Second * 10
106+
107+
// Return if the context has been canceled.
108+
select {
109+
case <-ctx.Done():
110+
return nil
111+
case <-timer.C:
112+
}
113+
114+
connectedFunc := func() {
115+
if !closedChan {
116+
close(readyChan)
117+
closedChan = true
118+
}
119+
// Reset the wait time to 10.
120+
waitTime = 10
121+
}
122+
123+
err := n.subscribeNotifications(ctx, connectedFunc)
124+
if err != nil {
125+
log.Errorf("Error subscribing to notifications: %v", err)
126+
}
127+
}
128+
}
129+
130+
// subscribeNotifications subscribes to the notifications from the server.
131+
func (m *Manager) subscribeNotifications(ctx context.Context,
132+
connectedFunc func()) error {
133+
134+
callCtx, cancel := context.WithCancel(ctx)
135+
defer cancel()
136+
137+
notifStream, err := m.cfg.Client.SubscribeNotifications(
138+
callCtx, &swapserverrpc.SubscribeNotificationsRequest{},
139+
)
140+
if err != nil {
141+
return err
142+
}
143+
144+
// Signal that we're connected to the server.
145+
connectedFunc()
146+
log.Debugf("Successfully subscribed to server notifications")
147+
148+
for {
149+
notification, err := notifStream.Recv()
150+
if err == nil && notification != nil {
151+
log.Debugf("Received notification: %v", notification)
152+
m.handleNotification(notification)
153+
continue
154+
}
155+
156+
log.Errorf("Error receiving notification: %v", err)
157+
158+
return err
159+
}
160+
}
161+
162+
// fetchL402 fetches the L402 from the server. This method will keep on
163+
// retrying until it gets a valid response.
164+
func (m *Manager) fetchL402(ctx context.Context) {
165+
// Add a 0 timer so that we initially fetch the L402 immediately.
166+
waitTime := time.Duration(0)
167+
timer := time.NewTimer(waitTime)
168+
for {
169+
select {
170+
case <-ctx.Done():
171+
return
172+
173+
case <-timer.C:
174+
err := m.cfg.FetchL402(ctx)
175+
if err != nil {
176+
log.Warnf("Error fetching L402: %v", err)
177+
waitTime += time.Second * 10
178+
timer.Reset(waitTime)
179+
continue
180+
}
181+
m.hasL402 = true
182+
183+
return
184+
}
185+
}
186+
}
187+
188+
// handleNotification handles an incoming notification from the server,
189+
// forwarding it to the appropriate subscribers.
190+
func (n *Manager) handleNotification(notification *swapserverrpc.
191+
SubscribeNotificationsResponse) {
192+
193+
switch notification.Notification.(type) {
194+
case *swapserverrpc.SubscribeNotificationsResponse_ReservationNotification:
195+
// We'll forward the reservation notification to all subscribers.
196+
// Cleaning up any subscribers that have been canceled.
197+
newSubs := make(
198+
[]subscriber, 0, len(n.subscribers[NotificationTypeReservation]),
199+
)
200+
reservationNtfn := notification.GetReservationNotification()
201+
for _, sub := range n.subscribers[NotificationTypeReservation] {
202+
recvChan := sub.recvChan.(chan *swapserverrpc.
203+
ServerReservationNotification)
204+
205+
select {
206+
case <-sub.subCtx.Done():
207+
close(recvChan)
208+
continue
209+
case recvChan <- reservationNtfn:
210+
newSubs = append(newSubs, sub)
211+
}
212+
}
213+
214+
n.Lock()
215+
n.subscribers[NotificationTypeReservation] = newSubs
216+
n.Unlock()
217+
218+
default:
219+
log.Warnf("Received unknown notification type: %v",
220+
notification)
221+
}
222+
}

0 commit comments

Comments
 (0)