github.com/aacfactory/fns@v1.2.86-0.20240310083819-80d667fc0a17/shareds/shared.go (about)

     1  /*
     2   * Copyright 2023 Wang Min Xiang
     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  
    18  package shareds
    19  
    20  import (
    21  	"github.com/aacfactory/configures"
    22  	"github.com/aacfactory/errors"
    23  	"github.com/aacfactory/json"
    24  	"github.com/aacfactory/logs"
    25  )
    26  
    27  type Options struct {
    28  	Log    logs.Logger
    29  	Config configures.Config
    30  }
    31  
    32  type Shared interface {
    33  	Construct(options Options) (err error)
    34  	Lockers() (lockers Lockers)
    35  	Store() (store Store)
    36  	Close()
    37  }
    38  
    39  type LocalSharedConfig struct {
    40  	Store json.RawMessage `json:"store,omitempty" yaml:"store,omitempty"`
    41  }
    42  
    43  func Local(log logs.Logger, config LocalSharedConfig) (v Shared, err error) {
    44  	if len(config.Store) == 0 {
    45  		config.Store = []byte{'{', '}'}
    46  	}
    47  	storeConfig, storeConfigErr := configures.NewJsonConfig(config.Store)
    48  	if storeConfigErr != nil {
    49  		err = errors.Warning("fns: build local shared failed").WithCause(storeConfigErr)
    50  		return
    51  	}
    52  	store, storeErr := localStoreBuilder(log, storeConfig)
    53  	if storeErr != nil {
    54  		err = errors.Warning("fns: build local shared failed").WithCause(storeErr)
    55  		return
    56  	}
    57  	v = &localShared{
    58  		lockers: LocalLockers(),
    59  		store:   store,
    60  	}
    61  	return
    62  }
    63  
    64  type localShared struct {
    65  	lockers Lockers
    66  	store   Store
    67  }
    68  
    69  func (s *localShared) Construct(_ Options) (err error) {
    70  	return
    71  }
    72  
    73  func (s *localShared) Lockers() (lockers Lockers) {
    74  	return s.lockers
    75  }
    76  
    77  func (s *localShared) Store() (store Store) {
    78  	return s.store
    79  }
    80  
    81  func (s *localShared) Close() {
    82  	s.store.Close()
    83  	s.lockers.Close()
    84  }