metaser

package module
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 17, 2025 License: Apache-2.0 Imports: 11 Imported by: 0

README

metaser

Go Reference

Metaser implements serialization and deserialization of structs into/from Kubernetes object's metadata. The primary use-case of this library is to allow easy storing of user-defined data structures in Kubernetes object's annotations and labels.

It's easy to use as it provides simple API and utilizes well-known struct tagging. Public API contains of just Encoder type with Encode method and Decoder type with Decode method. There are also Marshal and Unmarshal functions which provide same functionality without need to create Encoder or Decoder variables.

Example

type MyData struct {
    MyAnnotationVal int     `k8s:"annotation:myannotation,omitempty"`
    MyLabelVal      float32 `k8s:"label:mylabel,in"`
    MyNameVal       string  `k8s:"name,in"`
}

decoder := metaser.NewDecoder()
encoder := metaser.NewEncoder()

// meta is k8s.io/apimachinery/pkg/apis/meta/v1.Object and data is MyData.
if err := decoder.Decode(meta, &data); err != nil {
    log.Fatalln("unable to deserialize k8s object metadata to MyData struct")
}

// meta is k8s.io/apimachinery/pkg/apis/meta/v1.Object and data is MyData.
if err := encoder.Encode(&data, meta); err != nil {
    log.Fatalln("unable to serialize MyData to kubernetes object metadata")
}

Documentation

Overview

package metaser implements serialization and deserialization of structs into/from Kubernetes object's metadata.

The primary use-case of this library is to allow easy storing of user-defined data structures in Kubernetes object's annotations and labels.

Currently only 'name', 'namespace', 'labels', 'annotations' fields from Kubernets object's metadata are supported by metaser. metaser is using 'k8s' structure tag prefix for definiting serialization scheme.

Example:

type MyData struct {
  MyAnnotationVal int     `k8s:"annotation:myannotation,omitempty"`
  MyLabelVal      float32 `k8s:"label:mylabel,in"`
  MyNameVal       string  `k8s:"name,in"`
}

Supported tag values:

  • annotation - indicate if field should be serialized/deserialized from k8s Annotations map. The annotation should follow "annotation:<key>" syntax, where <key> should be valid k8s annotation
  • label - indicate if field should be serialized/deserialized from k8s Labels map. The annotation should follow "label:<key>" syntax, where <key> should be valid k8s label
  • name - indicate if field should be serialized/deserialized from k8s Name value.
  • namespace - indicate if field should be serialized/deserialized from k8s Namespace field value.
  • enc - sets encoding/decoding scheme for field. If ommited default schema will be used (see Supported types section for more info). If type is not in supported type list the TextMarshaler/TextUnmarshaler will be used. Tag should follow enc:<val> syntax, where val is one of supported values defined in Encoding schemes section.
  • in - indicate if field should be used during decoding and ignored during encoding
  • inout - indicate if field should be used during decoding and encoding. This is default value if 'in' or 'out' is not set explicitly.
  • out - indicate if field should be used during encoding and ignored during decoding
  • inline - can be only used on struct fields. Inline all contained structure fields into outer struct.
  • omitempty - do not encode field if have zero value. If the annotation or label exists it will be removed from metadata.
  • immutable - the value of field cannot change during decoding.
  • aliases - specify alternative keys for annotations or labels loopkup. Can be used only with 'annotation' or 'label' tag. The tag have following syntax: 'aliases:value1;value2;value3'. Values should be a valid k8s annotation or label key.
  • setonce - the value can change from zero value to non-zero value. It implies that field is immutable after set to non-zero value.

Encoding schemes:

  • json - field will deserialized/serialized with json decoder/encoder
  • custom - field will be deserialized/serialized with metaser.MetadataUnmarshaler/metaser.MetadataMarshaler interface.

Supported types:

  • bool - serialized/deserialized using strconv package.
  • int, int8, int16, int32, int64 - serialized/deserialized using strconv package.
  • uint, uint8, uint16, uint32, uint64 - serialized/deserialized using strconv package.
  • float32, float64 - serialized/deserialized using strconv package.
  • string
  • array - encodes field as comma separated list of elements. Serialized elements cannot contain comma.
  • slice - encodes field as comma separated list of elements. Serialized elements cannot contain comma.
  • map - encodes field as comma separated list of <key>:<value> pairs. Serialized elements cannot contain comma or semicolon.
  • pointers - pointers will be dereferenced during serialization/deserialization.
  • struct - structs can be only used with 'inline' tag.
  • metaser.Option[T] - generic struct representing optional value.

Limitations:

  • current implemntation does not support reference cycles inside decoded and encoded structs. The result of such operations is undefined.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetErrorList

func GetErrorList(err error) field.ErrorList

GetErrorList gets field.ErrorList type from underlying error.

func Marshal

func Marshal(v any, meta metav1.Object, options ...EncodeOption) error

Marshal reads data from v and writes it into K8s object metadata using default Encoder.

func Unmarshal

func Unmarshal(meta metav1.Object, v any, options ...DecodeOption) error

Unmarshal reads data from K8s object metadata using default Decoder.

Types

type DecodeOption

type DecodeOption func(dec *decodeContext)

DecodeOption to be passed to Decode()

func AccumulateFieldErrors

func AccumulateFieldErrors() DecodeOption

AccumulateFieldErrors enforces decoder to accumulate all encountered decode errors instead of aborting on first found one. the list of errors can be obtained with GetErrorList() function.

func DecodeImmutablesOnly

func DecodeImmutablesOnly() DecodeOption

DecodeImmutablesOnly option enforces Decoder to decode only annotations, labels and custom-encoded fields marked as immutable.

func Validate

func Validate(enabled bool) DecodeOption

Validate performs validation step in Decode()

type Decoder

type Decoder struct {
	// contains filtered or unexported fields
}

Decoder reads and decodes data from Kubernets Resource metatdata

func NewDecoder

func NewDecoder() *Decoder

NewDecoder returns new Decoder that reads data from meta.

func (*Decoder) Decode

func (dec *Decoder) Decode(meta metav1.Object, v any, options ...DecodeOption) error

Decode reads data from K8s object metadata and stores them in v.

See package documentation for details about deserialization.

type EncodeOption

type EncodeOption func(enc *encodeContext)

EncodeOption to be passed to Encode()

type Encoder

type Encoder struct{}

Encoder encodes and writes data into Kubernets Object's metatdata

func NewEncoder

func NewEncoder() *Encoder

NewEncoder returns new Encoder that writes data into meta.

func (*Encoder) Encode

func (*Encoder) Encode(v any, meta metav1.Object, options ...EncodeOption) error

Encode reads data from v and writes it into K8s object metadata.

See package documentation for details about serialization.

type MetadataMarshaler

type MetadataMarshaler interface {
	MarshalToMetadata(meta metav1.Object) error
}

type MetadataUnmarshaler

type MetadataUnmarshaler interface {
	UnmarshalFromMetadata(meta metav1.Object) error
}

type Option

type Option[T any] struct {
	// contains filtered or unexported fields
}

Option is a type representing optional value that may or may not be present.

func None

func None[T any]() Option[T]

None constructs new Option without value.

func Some

func Some[T any](value T) Option[T]

Some constructs new Option with value set to 'value'.

func (*Option[T]) Get

func (s *Option[T]) Get() T

Get gets contained value. If the values was not set it panics.

func (*Option[T]) GetOrDefault

func (s *Option[T]) GetOrDefault(def T) T

GetOrElse gets contained value. If the values was not set it returs other.

func (*Option[_]) IsSet

func (s *Option[_]) IsSet() bool

IsSet validates if internal option value was set.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL