github.com/minio/minio@v0.0.0-20240328213742-3f72439b8a27/internal/once/init.go (about)

     1  // Copyright (c) 2015-2023 MinIO, Inc.
     2  //
     3  // This file is part of MinIO Object Storage stack
     4  //
     5  // This program is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU Affero General Public License as published by
     7  // the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  //
    10  // This program is distributed in the hope that it will be useful
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13  // GNU Affero General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU Affero General Public License
    16  // along with this program.  If not, see <http://www.gnu.org/licenses/>.
    17  
    18  package once
    19  
    20  import (
    21  	"context"
    22  	"sync"
    23  	"sync/atomic"
    24  )
    25  
    26  // Inspired from Golang sync.Once but it is only marked
    27  // initialized when the provided function returns nil.
    28  
    29  // Init represents the structure.
    30  type Init struct {
    31  	done uint32
    32  	m    sync.Mutex
    33  }
    34  
    35  // Do is similar to sync.Once.Do - makes one successful
    36  // call to the function. ie, it invokes the function
    37  // if it is not successful yet.
    38  func (l *Init) Do(f func() error) error {
    39  	if atomic.LoadUint32(&l.done) == 0 {
    40  		return l.do(f)
    41  	}
    42  	return nil
    43  }
    44  
    45  func (l *Init) do(f func() error) error {
    46  	l.m.Lock()
    47  	defer l.m.Unlock()
    48  	if atomic.LoadUint32(&l.done) == 0 {
    49  		if err := f(); err != nil {
    50  			return err
    51  		}
    52  		// Mark as done only when f() is successful
    53  		atomic.StoreUint32(&l.done, 1)
    54  	}
    55  	return nil
    56  }
    57  
    58  // DoWithContext is similar to Do except that it accepts a context as an argument to be passed.
    59  func (l *Init) DoWithContext(ctx context.Context, f func(context.Context) error) error {
    60  	if atomic.LoadUint32(&l.done) == 0 {
    61  		return l.doWithContext(ctx, f)
    62  	}
    63  	return nil
    64  }
    65  
    66  func (l *Init) doWithContext(ctx context.Context, f func(context.Context) error) error {
    67  	l.m.Lock()
    68  	defer l.m.Unlock()
    69  	if atomic.LoadUint32(&l.done) == 0 {
    70  		if err := f(ctx); err != nil {
    71  			return err
    72  		}
    73  		// Mark as done only when f() is successful
    74  		atomic.StoreUint32(&l.done, 1)
    75  	}
    76  	return nil
    77  }