|
| 1 | +package authmailbox |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "net/url" |
| 7 | + "sync" |
| 8 | + |
| 9 | + "github.com/lightninglabs/taproot-assets/asset" |
| 10 | + lfn "github.com/lightningnetwork/lnd/fn/v2" |
| 11 | + "github.com/lightningnetwork/lnd/keychain" |
| 12 | +) |
| 13 | + |
| 14 | +// clientSubscriptions holds the subscriptions and cancel functions for a |
| 15 | +// specific mailbox client. |
| 16 | +type clientSubscriptions struct { |
| 17 | + // client is the mailbox client that this subscription belongs to. |
| 18 | + client *Client |
| 19 | + |
| 20 | + // subscriptions holds the active subscriptions for this client, keyed |
| 21 | + // by the serialized public key of the receiver. |
| 22 | + subscriptions map[asset.SerializedKey]ReceiveSubscription |
| 23 | + |
| 24 | + // cancels holds the cancel functions for each subscription, also keyed |
| 25 | + // by the serialized public key of the receiver. |
| 26 | + cancels map[asset.SerializedKey]context.CancelFunc |
| 27 | +} |
| 28 | + |
| 29 | +// MultiSubscription is a subscription manager that can handle multiple mailbox |
| 30 | +// clients, allowing subscriptions to different accounts across different |
| 31 | +// mailbox servers. It manages subscriptions and message queues for each client |
| 32 | +// and provides a unified interface for receiving messages. |
| 33 | +type MultiSubscription struct { |
| 34 | + // baseClientConfig holds the basic configuration for the mailbox |
| 35 | + // clients. All fields except the ServerAddress are used to create |
| 36 | + // new mailbox clients when needed. |
| 37 | + baseClientConfig ClientConfig |
| 38 | + |
| 39 | + // clients holds the active mailbox clients, keyed by their server URL. |
| 40 | + clients map[url.URL]*clientSubscriptions |
| 41 | + |
| 42 | + // msgQueue is the concurrent queue that holds received messages from |
| 43 | + // all subscriptions across all clients. This allows for a unified |
| 44 | + // message channel that can be used to receive messages from any |
| 45 | + // subscribed account, regardless of which mailbox server it belongs to. |
| 46 | + msgQueue *lfn.ConcurrentQueue[*ReceivedMessages] |
| 47 | + |
| 48 | + sync.RWMutex |
| 49 | +} |
| 50 | + |
| 51 | +// NewMultiSubscription creates a new MultiSubscription instance. |
| 52 | +func NewMultiSubscription(baseClientConfig ClientConfig) *MultiSubscription { |
| 53 | + queue := lfn.NewConcurrentQueue[*ReceivedMessages](lfn.DefaultQueueSize) |
| 54 | + queue.Start() |
| 55 | + |
| 56 | + return &MultiSubscription{ |
| 57 | + baseClientConfig: baseClientConfig, |
| 58 | + clients: make(map[url.URL]*clientSubscriptions), |
| 59 | + msgQueue: queue, |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +// Subscribe adds a new subscription for the specified client URL and receiver |
| 64 | +// key. It starts a new mailbox client if one does not already exist for the |
| 65 | +// given URL. The subscription will receive messages that match the provided |
| 66 | +// filter and will send them to the shared message queue. |
| 67 | +func (m *MultiSubscription) Subscribe(ctx context.Context, serverURL url.URL, |
| 68 | + receiverKey keychain.KeyDescriptor, filter MessageFilter) error { |
| 69 | + |
| 70 | + // We hold the mutex for access to common resources. |
| 71 | + m.Lock() |
| 72 | + cfgCopy := m.baseClientConfig |
| 73 | + client, ok := m.clients[serverURL] |
| 74 | + |
| 75 | + // If this is the first time we're seeing a server URL, we first create |
| 76 | + // a network connection to the mailbox server. |
| 77 | + if !ok { |
| 78 | + cfgCopy.ServerAddress = serverURL.Host |
| 79 | + |
| 80 | + mboxClient := NewClient(&cfgCopy) |
| 81 | + client = &clientSubscriptions{ |
| 82 | + client: mboxClient, |
| 83 | + subscriptions: make( |
| 84 | + map[asset.SerializedKey]ReceiveSubscription, |
| 85 | + ), |
| 86 | + cancels: make( |
| 87 | + map[asset.SerializedKey]context.CancelFunc, |
| 88 | + ), |
| 89 | + } |
| 90 | + m.clients[serverURL] = client |
| 91 | + |
| 92 | + err := mboxClient.Start() |
| 93 | + if err != nil { |
| 94 | + m.Unlock() |
| 95 | + return fmt.Errorf("unable to create mailbox client: %w", |
| 96 | + err) |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + // We release the lock here again, because StartAccountSubscription |
| 101 | + // might block for a while, and we don't want to hold the lock |
| 102 | + // unnecessarily long. |
| 103 | + m.Unlock() |
| 104 | + |
| 105 | + ctx, cancel := context.WithCancel(ctx) |
| 106 | + subscription, err := client.client.StartAccountSubscription( |
| 107 | + ctx, m.msgQueue.ChanIn(), receiverKey, filter, |
| 108 | + ) |
| 109 | + if err != nil { |
| 110 | + cancel() |
| 111 | + return fmt.Errorf("unable to start mailbox subscription: %w", |
| 112 | + err) |
| 113 | + } |
| 114 | + |
| 115 | + // We hold the lock again to safely add the subscription and cancel |
| 116 | + // function to the client's maps. |
| 117 | + m.Lock() |
| 118 | + key := asset.ToSerialized(receiverKey.PubKey) |
| 119 | + client.subscriptions[key] = subscription |
| 120 | + client.cancels[key] = cancel |
| 121 | + m.Unlock() |
| 122 | + |
| 123 | + return nil |
| 124 | +} |
| 125 | + |
| 126 | +// MessageChan returns a channel that can be used to receive messages from all |
| 127 | +// subscriptions across all mailbox clients. This channel will receive |
| 128 | +// ReceivedMessages, which contain the messages and their associated |
| 129 | +// metadata, such as the sender and receiver keys. |
| 130 | +func (m *MultiSubscription) MessageChan() <-chan *ReceivedMessages { |
| 131 | + return m.msgQueue.ChanOut() |
| 132 | +} |
| 133 | + |
| 134 | +// Stop stops all active subscriptions and mailbox clients. It cancels all |
| 135 | +// active subscription contexts and waits for all clients to stop gracefully. |
| 136 | +func (m *MultiSubscription) Stop() error { |
| 137 | + defer m.msgQueue.Stop() |
| 138 | + |
| 139 | + log.Info("Stopping all mailbox clients and subscriptions...") |
| 140 | + |
| 141 | + m.RLock() |
| 142 | + defer m.RUnlock() |
| 143 | + |
| 144 | + var lastErr error |
| 145 | + for _, client := range m.clients { |
| 146 | + for _, cancel := range client.cancels { |
| 147 | + cancel() |
| 148 | + } |
| 149 | + |
| 150 | + for _, sub := range client.subscriptions { |
| 151 | + err := sub.Stop() |
| 152 | + if err != nil { |
| 153 | + log.Errorf("Error stopping subscription: %v", |
| 154 | + err) |
| 155 | + lastErr = err |
| 156 | + } |
| 157 | + } |
| 158 | + |
| 159 | + if err := client.client.Stop(); err != nil { |
| 160 | + log.Errorf("Error stopping client: %v", err) |
| 161 | + lastErr = err |
| 162 | + } |
| 163 | + } |
| 164 | + |
| 165 | + return lastErr |
| 166 | +} |
0 commit comments