github.com/splunk/qbec@v0.15.2/vm/internal/ds/factory/lazy.go (about)

     1  /*
     2     Copyright 2021 Splunk Inc.
     3  
     4     Licensed under the Apache License, Version 2.0 (the "License");
     5     you may not use this file except in compliance with the License.
     6     You may obtain a copy of the License at
     7  
     8         http://www.apache.org/licenses/LICENSE-2.0
     9  
    10     Unless required by applicable law or agreed to in writing, software
    11     distributed under the License is distributed on an "AS IS" BASIS,
    12     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13     See the License for the specific language governing permissions and
    14     limitations under the License.
    15  */
    16  
    17  package factory
    18  
    19  import (
    20  	"sync"
    21  
    22  	"github.com/splunk/qbec/vm/datasource"
    23  	"github.com/splunk/qbec/vm/internal/ds"
    24  )
    25  
    26  // lazySource wraps a data source and defers initialization of its delegate until the first call to Resolve.
    27  // This allows data sources to be initialized before computed variables are, such that code in computed
    28  // variables can also refer to data sources.
    29  type lazySource struct {
    30  	delegate ds.DataSourceWithLifecycle
    31  	provider datasource.ConfigProvider
    32  	l        sync.Mutex
    33  	once     sync.Once
    34  	initErr  error
    35  }
    36  
    37  func makeLazy(delegate ds.DataSourceWithLifecycle) ds.DataSourceWithLifecycle {
    38  	return &lazySource{
    39  		delegate: delegate,
    40  	}
    41  }
    42  
    43  func (l *lazySource) Init(c datasource.ConfigProvider) error {
    44  	l.provider = c
    45  	return nil
    46  }
    47  
    48  func (l *lazySource) Name() string {
    49  	return l.delegate.Name()
    50  }
    51  
    52  func (l *lazySource) initOnce() error {
    53  	l.l.Lock()
    54  	defer l.l.Unlock()
    55  	l.once.Do(func() {
    56  		l.initErr = l.delegate.Init(l.provider)
    57  	})
    58  	return l.initErr
    59  }
    60  
    61  func (l *lazySource) Resolve(path string) (string, error) {
    62  	if err := l.initOnce(); err != nil {
    63  		return "", err
    64  	}
    65  	return l.delegate.Resolve(path)
    66  }
    67  
    68  func (l *lazySource) Close() error {
    69  	return l.delegate.Close()
    70  }
    71  
    72  var _ ds.DataSourceWithLifecycle = &lazySource{}