github.com/safing/portbase@v0.19.5/notifications/cleaner.go (about)

     1  package notifications
     2  
     3  import (
     4  	"context"
     5  	"time"
     6  )
     7  
     8  func cleaner(ctx context.Context) error { //nolint:unparam // Conforms to worker interface
     9  	ticker := module.NewSleepyTicker(1*time.Second, 0)
    10  	defer ticker.Stop()
    11  
    12  	for {
    13  		select {
    14  		case <-ctx.Done():
    15  			return nil
    16  		case <-ticker.Wait():
    17  			deleteExpiredNotifs()
    18  		}
    19  	}
    20  }
    21  
    22  func deleteExpiredNotifs() {
    23  	// Get a copy of the notification map.
    24  	notsCopy := getNotsCopy()
    25  
    26  	// Delete all expired notifications.
    27  	for _, n := range notsCopy {
    28  		if n.isExpired() {
    29  			n.delete(true)
    30  		}
    31  	}
    32  }
    33  
    34  func (n *Notification) isExpired() bool {
    35  	n.Lock()
    36  	defer n.Unlock()
    37  
    38  	return n.Expires > 0 && n.Expires < time.Now().Unix()
    39  }
    40  
    41  func getNotsCopy() []*Notification {
    42  	notsLock.RLock()
    43  	defer notsLock.RUnlock()
    44  
    45  	notsCopy := make([]*Notification, 0, len(nots))
    46  	for _, n := range nots {
    47  		notsCopy = append(notsCopy, n)
    48  	}
    49  
    50  	return notsCopy
    51  }