github.com/NVIDIA/aistore@v1.3.23-0.20240517131212-7df6609be51d/nl/notif.go (about)

     1  // Package notifications provides interfaces for AIStore notifications
     2  /*
     3   * Copyright (c) 2018-2024, NVIDIA CORPORATION. All rights reserved.
     4   */
     5  package nl
     6  
     7  import (
     8  	"time"
     9  
    10  	"github.com/NVIDIA/aistore/cmn"
    11  	"github.com/NVIDIA/aistore/cmn/atomic"
    12  	"github.com/NVIDIA/aistore/cmn/mono"
    13  	"github.com/NVIDIA/aistore/core"
    14  )
    15  
    16  type (
    17  	Base struct {
    18  		F func(n core.Notif, err error, aborted bool) // notification callback
    19  		P func(n core.Notif)                          // on progress notification callback
    20  
    21  		Dsts []string // node IDs to notify
    22  
    23  		When     core.Upon     // see the enum below
    24  		Interval time.Duration // interval at which progress needs to be updated
    25  
    26  		lastNotified atomic.Int64 // time when last notified
    27  	}
    28  )
    29  
    30  //////////
    31  // Base //
    32  //////////
    33  
    34  func (base *Base) OnFinishedCB() func(core.Notif, error, bool /*aborted*/) { return base.F }
    35  func (base *Base) OnProgressCB() func(core.Notif)                          { return base.P }
    36  func (base *Base) Upon(u core.Upon) bool                                   { return base != nil && base.When&u != 0 }
    37  func (base *Base) Subscribers() []string                                   { return base.Dsts }
    38  func (base *Base) LastNotifTime() int64                                    { return base.lastNotified.Load() }
    39  func (base *Base) SetLastNotified(now int64)                               { base.lastNotified.Store(now) }
    40  func (base *Base) NotifyInterval() time.Duration {
    41  	if base.Interval == 0 {
    42  		return cmn.GCO.Get().Periodic.NotifTime.D()
    43  	}
    44  	return base.Interval
    45  }
    46  
    47  //
    48  // common callbacks
    49  //
    50  
    51  func shouldNotify(n core.Notif) bool {
    52  	lastTime := n.LastNotifTime()
    53  	return lastTime == 0 || mono.Since(lastTime) > n.NotifyInterval()
    54  }
    55  
    56  func OnProgress(n core.Notif) {
    57  	if n == nil {
    58  		return
    59  	}
    60  	if cb := n.OnProgressCB(); cb != nil && shouldNotify(n) {
    61  		n.SetLastNotified(mono.NanoTime())
    62  		cb(n)
    63  	}
    64  }
    65  
    66  func OnFinished(n core.Notif, err error, aborted bool) {
    67  	if cb := n.OnFinishedCB(); cb != nil {
    68  		cb(n, err, aborted)
    69  	}
    70  }