github.com/pachyderm/pachyderm@v1.13.4/src/server/pkg/storage/renew/stringset.go (about) 1 package renew 2 3 import ( 4 "context" 5 "sync" 6 "time" 7 ) 8 9 // StringFunc is the type of a function used to renew a string 10 type StringFunc func(ctx context.Context, x string, ttl time.Duration) error 11 12 // StringSet renews a set of strings until it is closed 13 type StringSet struct { 14 *Renewer 15 mu sync.Mutex 16 set map[string]struct{} 17 } 18 19 // NewStringSet returns a StringSet it will renew every string in the set for ttl each period. 20 // See Renewer 21 func NewStringSet(ctx context.Context, ttl time.Duration, renewFunc StringFunc) *StringSet { 22 ss := &StringSet{ 23 set: map[string]struct{}{}, 24 } 25 ss.Renewer = NewRenewer(ctx, ttl, func(ctx context.Context, ttl time.Duration) error { 26 ss.mu.Lock() 27 defer ss.mu.Unlock() 28 for s := range ss.set { 29 if err := renewFunc(ctx, s, ttl); err != nil { 30 return err 31 } 32 } 33 return nil 34 }) 35 return ss 36 } 37 38 // Add adds x to the set of strings being renewed 39 func (ss *StringSet) Add(x string) { 40 ss.mu.Lock() 41 defer ss.mu.Unlock() 42 ss.set[x] = struct{}{} 43 } 44 45 // Remove removes x from the set of strings being renewed 46 func (ss *StringSet) Remove(x string) { 47 ss.mu.Lock() 48 defer ss.mu.Unlock() 49 delete(ss.set, x) 50 } 51 52 // WithStringSet creates a StringSet using ttl and rf. It calls cb with the StringSets context and the new StringSet. 53 // If ctx is cancelled, the StringSet will be Closed, and the cancellation will propagate down to the context passed to cb. 54 func WithStringSet(ctx context.Context, ttl time.Duration, rf StringFunc, cb func(ctx context.Context, ss *StringSet) error) (retErr error) { 55 ss := NewStringSet(ctx, ttl, rf) 56 defer func() { 57 if err := ss.Close(); retErr == nil { 58 retErr = err 59 } 60 }() 61 return cb(ss.Context(), ss) 62 }