Skip to content

Commit b2b9612

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 b2b9612

File tree

3 files changed

+405
-0
lines changed

3 files changed

+405
-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: 218 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,218 @@
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+
// Reset the wait time to 10 seconds 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+
}
120+
121+
err := n.subscribeNotifications(ctx, connectedFunc)
122+
if err != nil {
123+
log.Errorf("Error subscribing to notifications: %v", err)
124+
}
125+
}
126+
}
127+
128+
// subscribeNotifications subscribes to the notifications from the server.
129+
func (m *Manager) subscribeNotifications(ctx context.Context,
130+
connectedFunc func()) error {
131+
132+
callCtx, cancel := context.WithCancel(ctx)
133+
defer cancel()
134+
135+
notifStream, err := m.cfg.Client.SubscribeNotifications(
136+
callCtx, &swapserverrpc.SubscribeNotificationsRequest{},
137+
)
138+
if err != nil {
139+
return err
140+
}
141+
142+
// Signal that we're connected to the server.
143+
connectedFunc()
144+
log.Debugf("Successfully subscribed to server notifications")
145+
146+
for {
147+
notification, err := notifStream.Recv()
148+
if err == nil && notification != nil {
149+
log.Debugf("Received notification: %v", notification)
150+
m.handleNotification(notification)
151+
continue
152+
}
153+
154+
log.Errorf("Error receiving notification: %v", err)
155+
156+
return err
157+
}
158+
}
159+
160+
// fetchL402 fetches the L402 from the server. This method will keep on
161+
// retrying until it gets a valid response.
162+
func (m *Manager) fetchL402(ctx context.Context) {
163+
// Add a 0 timer so that we initially fetch the L402 immediately.
164+
timer := time.NewTimer(0)
165+
for {
166+
select {
167+
case <-ctx.Done():
168+
return
169+
170+
case <-timer.C:
171+
err := m.cfg.FetchL402(ctx)
172+
if err != nil {
173+
log.Warnf("Error fetching L402: %v", err)
174+
timer.Reset(time.Second * 10)
175+
continue
176+
}
177+
m.hasL402 = true
178+
179+
return
180+
}
181+
}
182+
}
183+
184+
// handleNotification handles an incoming notification from the server,
185+
// forwarding it to the appropriate subscribers.
186+
func (n *Manager) handleNotification(notification *swapserverrpc.
187+
SubscribeNotificationsResponse) {
188+
189+
switch notification.Notification.(type) {
190+
case *swapserverrpc.SubscribeNotificationsResponse_ReservationNotification:
191+
// We'll forward the reservation notification to all subscribers.
192+
// Cleaning up any subscribers that have been canceled.
193+
newSubs := make(
194+
[]subscriber, 0, len(n.subscribers[NotificationTypeReservation]),
195+
)
196+
reservationNtfn := notification.GetReservationNotification()
197+
for _, sub := range n.subscribers[NotificationTypeReservation] {
198+
recvChan := sub.recvChan.(chan *swapserverrpc.
199+
ServerReservationNotification)
200+
201+
select {
202+
case <-sub.subCtx.Done():
203+
close(recvChan)
204+
continue
205+
case recvChan <- reservationNtfn:
206+
newSubs = append(newSubs, sub)
207+
}
208+
}
209+
210+
n.Lock()
211+
n.subscribers[NotificationTypeReservation] = newSubs
212+
n.Unlock()
213+
214+
default:
215+
log.Warnf("Received unknown notification type: %v",
216+
notification)
217+
}
218+
}

0 commit comments

Comments
 (0)