github.com/hernad/nomad@v1.6.112/helper/pluginutils/singleton/future.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: MPL-2.0
     3  
     4  package singleton
     5  
     6  import (
     7  	"github.com/hernad/nomad/helper/pluginutils/loader"
     8  	"github.com/hernad/nomad/helper/uuid"
     9  )
    10  
    11  // future is a sharable future for retrieving a plugin instance or any error
    12  // that may have occurred during the creation.
    13  type future struct {
    14  	waitCh chan struct{}
    15  	id     string
    16  
    17  	err      error
    18  	instance loader.PluginInstance
    19  }
    20  
    21  // newFuture returns a new pull future
    22  func newFuture() *future {
    23  	return &future{
    24  		waitCh: make(chan struct{}),
    25  		id:     uuid.Generate(),
    26  	}
    27  }
    28  
    29  func (f *future) equal(o *future) bool {
    30  	if f == nil && o == nil {
    31  		return true
    32  	} else if f != nil && o != nil {
    33  		return f.id == o.id
    34  	} else {
    35  		return false
    36  	}
    37  }
    38  
    39  // wait waits till the future has a result
    40  func (f *future) wait() *future {
    41  	<-f.waitCh
    42  	return f
    43  }
    44  
    45  // result returns the results of the future and should only ever be called after
    46  // wait returns.
    47  func (f *future) result() (loader.PluginInstance, error) {
    48  	return f.instance, f.err
    49  }
    50  
    51  // set is used to set the results and unblock any waiter. This may only be
    52  // called once.
    53  func (f *future) set(instance loader.PluginInstance, err error) {
    54  	f.instance = instance
    55  	f.err = err
    56  	close(f.waitCh)
    57  }