github.com/aacfactory/fns@v1.2.86-0.20240310083819-80d667fc0a17/services/components.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 services
    19  
    20  import (
    21  	"fmt"
    22  	"github.com/aacfactory/errors"
    23  	"github.com/aacfactory/fns/context"
    24  )
    25  
    26  var (
    27  	contextComponentsKeyPrefix = []byte("@fns:service:components:")
    28  )
    29  
    30  type Component interface {
    31  	Name() (name string)
    32  	Construct(options Options) (err error)
    33  	Shutdown(ctx context.Context)
    34  }
    35  
    36  type Components []Component
    37  
    38  func (components Components) Get(name string) (v Component, has bool) {
    39  	for _, component := range components {
    40  		if component.Name() == name {
    41  			v = component
    42  			has = true
    43  			return
    44  		}
    45  	}
    46  	return
    47  }
    48  
    49  func WithComponents(ctx context.Context, service []byte, components Components) {
    50  	ctx.SetLocalValue(append(contextComponentsKeyPrefix, service...), components)
    51  }
    52  
    53  func LoadComponents(ctx context.Context, service []byte) Components {
    54  	v := ctx.LocalValue(append(contextComponentsKeyPrefix, service...))
    55  	if v == nil {
    56  		return nil
    57  	}
    58  	c, ok := v.(Components)
    59  	if !ok {
    60  		panic(fmt.Sprintf("%+v", errors.Warning("fns: components in context is not github.com/aacfactory/fns/services.Components")))
    61  		return nil
    62  	}
    63  	return c
    64  }
    65  
    66  func LoadComponent[C Component](ctx context.Context, service []byte, name string) (c C, has bool) {
    67  	cc := LoadComponents(ctx, service)
    68  	if len(cc) == 0 {
    69  		return
    70  	}
    71  	v, exist := cc.Get(name)
    72  	if !exist {
    73  		return
    74  	}
    75  	c, has = v.(C)
    76  	return
    77  }