go.ligato.io/vpp-agent/v3@v3.5.0/pkg/models/spec.go (about)

     1  package models
     2  
     3  import (
     4  	"fmt"
     5  	"regexp"
     6  	"strings"
     7  
     8  	api "go.ligato.io/vpp-agent/v3/proto/ligato/generic"
     9  )
    10  
    11  var (
    12  	validModule  = regexp.MustCompile(`^[-a-z0-9_]+(?:\.[-a-z0-9_]+)?$`)
    13  	validVersion = regexp.MustCompile(`^v[0-9]+(?:[-a-z0-9]+)?$`)
    14  	validType    = regexp.MustCompile(`^[-a-z0-9_]+(?:\.[-a-z0-9_]+)?$`)
    15  	validClass   = regexp.MustCompile(`^[-a-z0-9_]+$`)
    16  )
    17  
    18  // Spec defines model specification used for registering model.
    19  type Spec struct {
    20  	Module  string
    21  	Version string
    22  	Type    string
    23  	Class   string
    24  }
    25  
    26  func ToSpec(s *api.ModelSpec) Spec {
    27  	return Spec{
    28  		Module:  s.GetModule(),
    29  		Version: s.GetVersion(),
    30  		Type:    s.GetType(),
    31  		Class:   s.GetClass(),
    32  	}
    33  }
    34  
    35  func (spec Spec) Proto() *api.ModelSpec {
    36  	return &api.ModelSpec{
    37  		Module:  spec.Module,
    38  		Version: spec.Version,
    39  		Type:    spec.Type,
    40  		Class:   spec.Class,
    41  	}
    42  }
    43  
    44  func (spec Spec) KeyPrefix() string {
    45  	modulePath := strings.Replace(spec.Module, ".", "/", -1)
    46  	typePath := strings.Replace(spec.Type, ".", "/", -1)
    47  	return fmt.Sprintf("%s/%s/%s/%s/", spec.Class, modulePath, spec.Version, typePath)
    48  }
    49  
    50  func (spec Spec) ModelName() string {
    51  	return fmt.Sprintf("%s.%s", spec.Module, spec.Type)
    52  }
    53  
    54  // Validate validates Spec fields.
    55  func (spec Spec) Validate() error {
    56  	if !validModule.MatchString(spec.Module) {
    57  		return fmt.Errorf("invalid module: %q", spec.Module)
    58  	}
    59  	if !validVersion.MatchString(spec.Version) {
    60  		return fmt.Errorf("invalid version: %q", spec.Version)
    61  	}
    62  	if !validType.MatchString(spec.Type) {
    63  		return fmt.Errorf("invalid type: %q", spec.Type)
    64  	}
    65  	if !validClass.MatchString(spec.Class) {
    66  		return fmt.Errorf("invalid class: %q", spec.Class)
    67  	}
    68  	return nil
    69  }