github.com/authzed/spicedb@v1.32.1-0.20240520085336-ebda56537386/pkg/caveats/types/types.go (about)

     1  package types
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	"github.com/authzed/cel-go/cel"
     8  	"golang.org/x/exp/maps"
     9  )
    10  
    11  // VariableType defines the supported types of variables in caveats.
    12  type VariableType struct {
    13  	localName  string
    14  	celType    *cel.Type
    15  	childTypes []VariableType
    16  	converter  typedValueConverter
    17  }
    18  
    19  // CelType returns the underlying CEL type for the variable type.
    20  func (vt VariableType) CelType() *cel.Type {
    21  	return vt.celType
    22  }
    23  
    24  func (vt VariableType) String() string {
    25  	if len(vt.childTypes) > 0 {
    26  		childTypeStrings := make([]string, 0, len(vt.childTypes))
    27  		for _, childType := range vt.childTypes {
    28  			childTypeStrings = append(childTypeStrings, childType.String())
    29  		}
    30  
    31  		return vt.localName + "<" + strings.Join(childTypeStrings, ", ") + ">"
    32  	}
    33  
    34  	return vt.localName
    35  }
    36  
    37  // ConvertValue converts the given value into one expected by this variable type.
    38  func (vt VariableType) ConvertValue(value any) (any, error) {
    39  	converted, err := vt.converter(value)
    40  	if err != nil {
    41  		return nil, fmt.Errorf("for %s: %w", vt.String(), err)
    42  	}
    43  
    44  	return converted, nil
    45  }
    46  
    47  // TypeKeywords returns all keywords associated with types.
    48  func TypeKeywords() []string {
    49  	return maps.Keys(definitions)
    50  }
    51  
    52  // BuildType builds a variable type from its name and child types.
    53  func BuildType(name string, childTypes []VariableType) (*VariableType, error) {
    54  	typeDef, ok := definitions[name]
    55  	if !ok {
    56  		return nil, fmt.Errorf("unknown type `%s`", name)
    57  	}
    58  
    59  	return typeDef.asVariableType(childTypes)
    60  }