Skip to content

Commit

Permalink
mint - shutdown websocket manager and invoice subscriptions on mint s…
Browse files Browse the repository at this point in the history
…hutdown
  • Loading branch information
elnosh committed Feb 7, 2025
1 parent 9ac39b9 commit dafe95a
Show file tree
Hide file tree
Showing 9 changed files with 58 additions and 22 deletions.
12 changes: 9 additions & 3 deletions mint/invoicesub.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package mint

import (
"context"
"encoding/json"
"errors"
"time"

"github.com/elnosh/gonuts/cashu/nuts/nut04"
Expand All @@ -10,14 +12,14 @@ import (

// checkInvoicePaid should be called in a different goroutine to check in the background
// if the invoice for the quoteId gets paid and update it in the db.
func (m *Mint) checkInvoicePaid(quoteId string) {
func (m *Mint) checkInvoicePaid(ctx context.Context, quoteId string) {
mintQuote, err := m.db.GetMintQuote(quoteId)
if err != nil {
m.logErrorf("could not get mint quote '%v' from db: %v", quoteId, err)
return
}

invoiceSub, err := m.lightningClient.SubscribeInvoice(mintQuote.PaymentHash)
invoiceSub, err := m.lightningClient.SubscribeInvoice(ctx, mintQuote.PaymentHash)
if err != nil {
m.logErrorf("could not subscribe to invoice changes for mint quote '%v': %v", quoteId, err)
return
Expand Down Expand Up @@ -56,7 +58,11 @@ func (m *Mint) checkInvoicePaid(quoteId string) {
m.publisher.Publish(BOLT11_MINT_QUOTE_TOPIC, jsonQuote)
}
case err := <-errChan:
m.logErrorf("error reading from invoice subscription: %v", err)
if errors.Is(ctx.Err(), context.Canceled) {
m.logDebugf("canceling invoice subscription for quote '%v'. Context canceled", mintQuote.Id)
} else {
m.logErrorf("error reading from invoice subscription: %v", err)
}
case <-time.After(time.Second * time.Duration(timeUntilExpiry)):
// cancel when quote reaches expiry time
m.logDebugf("canceling invoice subscription for quote '%v'. Reached deadline", mintQuote.Id)
Expand Down
2 changes: 1 addition & 1 deletion mint/lightning/fakebackend.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ func (fb *FakeBackend) FeeReserve(amount uint64) uint64 {
return 0
}

func (fb *FakeBackend) SubscribeInvoice(paymentHash string) (InvoiceSubscriptionClient, error) {
func (fb *FakeBackend) SubscribeInvoice(ctx context.Context, paymentHash string) (InvoiceSubscriptionClient, error) {
return &FakeInvoiceSub{
paymentHash: paymentHash,
fb: fb,
Expand Down
2 changes: 1 addition & 1 deletion mint/lightning/lightning.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ type Client interface {
PayPartialAmount(ctx context.Context, request string, amountMsat uint64, maxFee uint64) (PaymentStatus, error)
OutgoingPaymentStatus(ctx context.Context, hash string) (PaymentStatus, error)
FeeReserve(amount uint64) uint64
SubscribeInvoice(paymentHash string) (InvoiceSubscriptionClient, error)
SubscribeInvoice(ctx context.Context, paymentHash string) (InvoiceSubscriptionClient, error)
}

type Invoice struct {
Expand Down
4 changes: 2 additions & 2 deletions mint/lightning/lnd.go
Original file line number Diff line number Diff line change
Expand Up @@ -249,15 +249,15 @@ func (lnd *LndClient) FeeReserve(amount uint64) uint64 {
return uint64(fee)
}

func (lnd *LndClient) SubscribeInvoice(paymentHash string) (InvoiceSubscriptionClient, error) {
func (lnd *LndClient) SubscribeInvoice(ctx context.Context, paymentHash string) (InvoiceSubscriptionClient, error) {
hash, err := hex.DecodeString(paymentHash)
if err != nil {
return nil, err
}
invoiceSubRequest := &invoicesrpc.SubscribeSingleInvoiceRequest{
RHash: hash,
}
lndInvoiceClient, err := lnd.invoicesClient.SubscribeSingleInvoice(context.Background(), invoiceSubRequest)
lndInvoiceClient, err := lnd.invoicesClient.SubscribeSingleInvoice(ctx, invoiceSubRequest)
if err != nil {
return nil, err
}
Expand Down
12 changes: 11 additions & 1 deletion mint/mint.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ type Mint struct {
mppEnabled bool

publisher *pubsub.PubSub
ctx context.Context
cancel context.CancelFunc
}

func LoadMint(config Config) (*Mint, error) {
Expand Down Expand Up @@ -107,6 +109,7 @@ func LoadMint(config Config) (*Mint, error) {
return nil, err
}
logger.Info(fmt.Sprintf("setting active keyset '%v' with fee %v", activeKeyset.Id, activeKeyset.InputFeePpk))
ctx, cancel := context.WithCancel(context.Background())

mint := &Mint{
db: db,
Expand All @@ -115,6 +118,8 @@ func LoadMint(config Config) (*Mint, error) {
logger: logger,
mppEnabled: config.EnableMPP,
publisher: pubsub.NewPubSub(),
ctx: ctx,
cancel: cancel,
}

dbKeysets, err := mint.db.GetKeysets()
Expand Down Expand Up @@ -248,6 +253,11 @@ func (m *Mint) logDebugf(format string, args ...any) {
_ = m.logger.Handler().Handle(context.Background(), r)
}

func (m *Mint) Shutdown() error {
m.cancel()
return m.db.Close()
}

// RequestMintQuote will process a request to mint tokens
// and returns a mint quote or an error.
// The request to mint a token is explained in
Expand Down Expand Up @@ -306,7 +316,7 @@ func (m *Mint) RequestMintQuote(mintQuoteRequest nut04.PostMintQuoteBolt11Reques
}

// goroutine to check in the background when invoice gets paid and update db if so
go m.checkInvoicePaid(quoteId)
go m.checkInvoicePaid(m.ctx, quoteId)

return mintQuote, nil
}
Expand Down
14 changes: 11 additions & 3 deletions mint/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,18 @@ func SetupMintServer(config Config) (*MintServer, error) {
return mintServer, nil
}

func (ms *MintServer) Shutdown() {
func (ms *MintServer) Shutdown() error {
ms.mint.logger.Info("starting shutdown")
ms.mint.db.Close()
ms.httpServer.Shutdown(context.Background())
if err := ms.mint.Shutdown(); err != nil {
return err
}
if err := ms.websocketManager.Shutdown(); err != nil {
return err
}
if err := ms.httpServer.Shutdown(context.Background()); err != nil {
return err
}
return nil
}

func (ms *MintServer) setupHttpServer(port int) error {
Expand Down
4 changes: 2 additions & 2 deletions mint/storage/sqlite/sqlite.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,8 @@ func InitSQLite(path string) (*SQLiteDB, error) {
return &SQLiteDB{db: db}, nil
}

func (sqlite *SQLiteDB) Close() {
sqlite.db.Close()
func (sqlite *SQLiteDB) Close() error {
return sqlite.db.Close()
}

func (sqlite *SQLiteDB) GetBalance() (uint64, error) {
Expand Down
2 changes: 1 addition & 1 deletion mint/storage/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ type MintDB interface {
GetBlindSignature(B_ string) (cashu.BlindedSignature, error)
GetBlindSignatures(B_s []string) (cashu.BlindedSignatures, error)

Close()
Close() error
}

type DBKeyset struct {
Expand Down
28 changes: 20 additions & 8 deletions mint/websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ var upgrader = websocket.Upgrader{

type WebsocketManager struct {
clients map[*Client]bool
sync.RWMutex
mint *Mint
mu sync.RWMutex
mint *Mint
}

func NewWebSocketManager(mint *Mint) *WebsocketManager {
Expand All @@ -58,18 +58,30 @@ func (wm *WebsocketManager) serveWS(w http.ResponseWriter, r *http.Request) {
}

func (wm *WebsocketManager) addClient(client *Client) {
wm.Lock()
wm.mu.Lock()
wm.clients[client] = true
wm.Unlock()
wm.mu.Unlock()
}

func (wm *WebsocketManager) removeClient(client *Client) {
wm.Lock()
func (wm *WebsocketManager) removeClient(client *Client) error {
wm.mu.Lock()
if _, ok := wm.clients[client]; ok {
client.close()
if err := client.close(); err != nil {
return err
}
delete(wm.clients, client)
}
wm.Unlock()
wm.mu.Unlock()
return nil
}

func (wm *WebsocketManager) Shutdown() error {
for client := range wm.clients {
if err := wm.removeClient(client); err != nil {
return err
}
}
return nil
}

type Client struct {
Expand Down

0 comments on commit dafe95a

Please sign in to comment.