hz

package
v0.0.0-...-c966403 Latest Latest
Warning

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

Go to latest
Published: Mar 16, 2024 License: Apache-2.0 Imports: 29 Imported by: 0

Documentation

Index

Constants

View Source
const (
	BucketObjects = "hz_objects"
	BucketMutex   = "hz_objects_mutex"
)
View Source
const (
	HeaderStatus              = "Hz-Status"
	HeaderAuthorization       = "Hz-Authorization"
	HeaderApplyFieldManager   = "Hz-Apply-Field-Manager"
	HeaderApplyForceConflicts = "Hz-Apply-Force-Conflicts"
)
View Source
const (
	SubjectAPIAllowAll = "HZ.api.>"

	// format: HZ.api.broker.<group>.<version>.<kind>.<account>.<name>.<action>
	SubjectAPIBroker                  = "HZ.api.broker.*.*.*.*.*.*"
	SubjectInternalBroker             = "HZ.internal.broker.*.*.*.*.*.*"
	SubjectInternalBrokerIndexGroup   = 3
	SubjectInternalBrokerIndexVersion = 4
	SubjectInternalBrokerIndexKind    = 5
	SubjectInternalBrokerIndexAccount = 6
	SubjectInternalBrokerIndexName    = 7
	SubjectInternalBrokerIndexAction  = 8
	SubjectInternalBrokerLength       = 9
	SubjectBrokerRun                  = "broker.%s.%s.%s.%s.%s.%s"

	// format:
	// HZ.internal.actor.advertise.<group>.<version>.<kind>.<account>.<name>.<action>
	SubjectActorAdvertise    = "HZ.internal.actor.advertise.%s.%s.%s.*.*.%s"
	SubjectActorAdvertiseFmt = "HZ.internal.actor.advertise.%s.%s.%s.%s.%s.%s"
	// format:
	// HZ.internal.actor.run.<group>.<version>.<kind>.<account>.<name>.<action>.<actor_uuid>
	SubjectActorRun    = "HZ.internal.actor.run.%s.%s.%s.*.*.%s.%s"
	SubjectActorRunFmt = "HZ.internal.actor.run.%s.%s.%s.%s.%s.%s.%s"
)
View Source
const (
	// format: HZ.internal.controller.schema.<group>.<version>.<kind>
	SubjectCtlrSchema         = "HZ.internal.controller.schema.%s.%s.%s"
	SubjectCtlrValidateCreate = "HZ.internal.controller.validate_create.%s.%s.%s"
	SubjectCtlrValidateUpdate = "HZ.internal.controller.validate_update.%s.%s.%s"
)
View Source
const (
	// Format: store.<cmd>.<group>.<version>.<kind>
	SubjectStoreSchema   = "store.schema.%s.%s.%s"
	SubjectStoreValidate = "store.validate.%s.%s.%s"
	// Format: store.<cmd>.<group>.<version>.<kind>.<account>.<name>
	SubjectStoreApply  = "store.apply.%s.%s.%s.%s.%s"
	SubjectStoreCreate = "store.create.%s.%s.%s.%s.%s"
	SubjectStoreGet    = "store.get.%s.%s.%s.%s.%s"
	SubjectStoreDelete = "store.delete.%s.%s.%s.%s.%s"
	SubjectStoreList   = "store.list.%s.%s.%s.%s.%s"
)
View Source
const (
	SchemaTypeArray   = SchemaType("array")
	SchemaTypeBoolean = SchemaType("boolean")
	SchemaTypeInteger = SchemaType("integer")
	SchemaTypeNumber  = SchemaType("number")
	SchemaTypeObject  = SchemaType("object")
	SchemaTypeString  = SchemaType("string")
)

SchemaType values enumeration.

View Source
const (
	RequestPortal  = "HZ-Request-Portal"
	RequestAccount = "HZ-Request-Account"
)
View Source
const (
	CookieSession = "hz_session"
)
View Source
const RootAccount = "hz-root"
View Source
const SubjectPortalRender = "HZ.internal.portal.%s.http.render"

Variables

View Source
var (
	ErrNoRevision        = errors.New("no revision")
	ErrIncorrectRevision = errors.New("incorrect revision")
	ErrNotFound          = &Error{
		Status:  http.StatusNotFound,
		Message: "not found",
	}
	ErrApplyManagerRequired       = errors.New("apply: field manager required")
	ErrClientObjectOrDataRequired = errors.New("object or data required")
	ErrClientNoSession            = errors.New("client: no session")

	ErrStoreNotResponding = errors.New("store: not responding")

	ErrRunNoResponders         = errors.New("run: no brokers responding")
	ErrRunTimeout              = errors.New("run: broker timeout")
	ErrBrokerNoActorResponders = errors.New("broker: no actor responders")
	ErrBrokerActorTimeout      = errors.New("broker: actor timeout")
)
View Source
var ErrKeyLocked = errors.New("key locked")

Functions

func ErrorFromHTTP

func ErrorFromHTTP(resp *http.Response) error

func ErrorFromNATS

func ErrorFromNATS(msg *nats.Msg) error

func ErrorFromNATSErr

func ErrorFromNATSErr(err error) error

func ErrorWrap

func ErrorWrap(
	err error,
	status int,
	message string,
) error

ErrorWrap takes an error and checks if it is an Error. If it is, it will make a copy of the Error, add the given message and return it. The status will remain the same.

If it is not an Error, it will wrap the given error in an Error with the given status and message.

func ExtractManagedFields

func ExtractManagedFields[T Objecter](
	object T,
	manager string,
) (T, error)

ExtractManagedFields creates an object containing the fields managed by the given manager. If the manager does not manage any fields, the object will be empty (except for the identifying fields, like metadata.name, metadata.account).

The use of ExtractManagedFields is for a controller (for example) to get an object from the store, extract the fields it manages, and then update the object with the managed fields.

func IgnoreNotFound

func IgnoreNotFound(err error) error

func KeyFromObject

func KeyFromObject(obj ObjectKeyer) string

KeyFromObject takes an ObjectKeyer and returns a string key. Any empty fields in the ObjectKeyer are replaced with "*" which works well for nats subjects to list objects.

If performing an action on a specific object (e.g. get, create, apply) the key cannot contain "*". In this case you can use KeyFromObjectStrict which makes sure the ObjectKeyer is concrete.

func KeyFromObjectStrict

func KeyFromObjectStrict(obj ObjectKeyer) (string, error)

KeyFromObjectStrict takes an ObjectKeyer and returns a string key. It returns an error if any of the fields are empty (except APIVersion). This is useful when you want to ensure the key is concrete when performing operations on specific objects (e.g. get, create, apply).

func MutexFromBucket

func MutexFromBucket(
	ctx context.Context,
	js jetstream.JetStream,
	bucket string,
) (mutex, error)

func OpenAPIFromObject

func OpenAPIFromObject(obj Objecter) ([]byte, error)

func P

func P[T any](v T) *T

func RespondError

func RespondError(
	msg *nats.Msg,
	err error,
) error

respondError responds to a NATS message with an error. It expects the err to be an *Error and will use the status and message for the response. If not, it will use a http.StatusInternalServerError.

func RespondOK

func RespondOK(
	msg *nats.Msg,
	body []byte,
) error

func RespondStatus

func RespondStatus(
	msg *nats.Msg,
	status int,
	body []byte,
) error

func SessionFromRequest

func SessionFromRequest(req *http.Request) string

Types

type Action

type Action[T Objecter] interface {
	Actioner
	Do(context.Context, T) (T, error)
}

type Actioner

type Actioner interface {
	Action() string
}

type Actor

type Actor[T Objecter] struct {
	// contains filtered or unexported fields
}

func StartActor

func StartActor[T Objecter](
	ctx context.Context,
	nc *nats.Conn,
	opts ...ActorOption[T],
) (*Actor[T], error)

func (*Actor[T]) Start

func (a *Actor[T]) Start(ctx context.Context, opts ...ActorOption[T]) error

func (*Actor[T]) Stop

func (a *Actor[T]) Stop() error

type ActorOption

type ActorOption[T Objecter] func(*actorOption[T])

func WithActorActioner

func WithActorActioner[T Objecter](
	actioner Action[T],
) ActorOption[T]

func WithActorLabels

func WithActorLabels[T Objecter](
	labels map[string]string,
) ActorOption[T]

type AdvertiseMsg

type AdvertiseMsg struct {
	LabelSelector LabelSelector `json:"labelSelector,omitempty"`
}

type ApplyOpResult

type ApplyOpResult string
const (
	ApplyOpResultCreated  ApplyOpResult = "created"
	ApplyOpResultUpdated  ApplyOpResult = "updated"
	ApplyOpResultNoop     ApplyOpResult = "noop"
	ApplyOpResultConflict ApplyOpResult = "conflict"
	ApplyOpResultError    ApplyOpResult = "error"
)

type ApplyOption

type ApplyOption func(*applyOptions)

func WithApplyData

func WithApplyData(data []byte) ApplyOption

func WithApplyForce

func WithApplyForce(force bool) ApplyOption

func WithApplyObject

func WithApplyObject(object Objecter) ApplyOption

type CUEValidator

type CUEValidator struct {
	Object Objecter
	// contains filtered or unexported fields
}

func (*CUEValidator) ParseObject

func (v *CUEValidator) ParseObject() error

func (*CUEValidator) ValidateCreate

func (v *CUEValidator) ValidateCreate(ctx context.Context, data []byte) error

func (*CUEValidator) ValidateDelete

func (v *CUEValidator) ValidateDelete(ctx context.Context, data []byte) error

func (*CUEValidator) ValidateUpdate

func (v *CUEValidator) ValidateUpdate(
	ctx context.Context,
	old []byte,
	data []byte,
) error

type Client

type Client struct {
	Conn *nats.Conn

	// Internal is set to true to use the internal nats subjects.
	// This is used for service accounts (controllers) that have nats
	// credentials with permission to use the internal nats subjects.
	// For clients such as hzctl, this should be false causing the client to use
	// the `api` nats subjects (requiring authn/authz).
	Internal bool

	Session string

	// Manager is the manager of apply operations.
	Manager string
}

func NewClient

func NewClient(conn *nats.Conn, opts ...ClientOption) Client

func (Client) Apply

func (c Client) Apply(
	ctx context.Context,
	opts ...ApplyOption,
) (ApplyOpResult, error)

func (*Client) Create

func (c *Client) Create(
	ctx context.Context,
	opts ...CreateOption,
) error

func (*Client) Delete

func (c *Client) Delete(
	ctx context.Context,
	opts ...DeleteOption,
) error

func (*Client) Get

func (c *Client) Get(
	ctx context.Context,
	opts ...GetOption,
) ([]byte, error)

func (*Client) List

func (c *Client) List(
	ctx context.Context,
	opts ...ListOption,
) error

func (*Client) Run

func (c *Client) Run(
	ctx context.Context,
	opts ...RunOption,
) ([]byte, error)

func (Client) Schema

func (c Client) Schema(
	ctx context.Context,
	key ObjectKeyer,
) (Schema, error)

func (Client) SubjectPrefix

func (c Client) SubjectPrefix() string

func (Client) Validate

func (c Client) Validate(
	ctx context.Context,
	opts ...ValidateOption,
) error

type ClientOption

type ClientOption func(*clientOpts)

func WithClientDefaultManager

func WithClientDefaultManager() ClientOption

func WithClientInternal

func WithClientInternal(b bool) ClientOption

func WithClientManager

func WithClientManager(manager string) ClientOption

func WithClientSession

func WithClientSession(session string) ClientOption

func WithClientSessionFromRequest

func WithClientSessionFromRequest(req *http.Request) ClientOption

type Components

type Components struct {
	Schemas map[string]Schema `json:"schemas,omitempty"`
}

type Controller

type Controller struct {
	Conn *nats.Conn
	// contains filtered or unexported fields
}

func StartController

func StartController(
	ctx context.Context,
	nc *nats.Conn,
	opts ...ControllerOption,
) (*Controller, error)

func (*Controller) Start

func (c *Controller) Start(
	ctx context.Context,
	opts ...ControllerOption,
) error

func (*Controller) Stop

func (c *Controller) Stop() error

type ControllerOption

type ControllerOption func(*controllerOption)

func WithControllerBucket

func WithControllerBucket(bucketObjects string) ControllerOption

func WithControllerFor

func WithControllerFor(obj Objecter) ControllerOption

func WithControllerOwns

func WithControllerOwns(obj Objecter) ControllerOption

func WithControllerReconciler

func WithControllerReconciler(reconciler Reconciler) ControllerOption

func WithControllerStopTimeout

func WithControllerStopTimeout(d time.Duration) ControllerOption

func WithControllerValidator

func WithControllerValidator(validator Validator) ControllerOption

func WithControllerValidatorCUE

func WithControllerValidatorCUE(b bool) ControllerOption

func WithControllerValidatorForceNone

func WithControllerValidatorForceNone() ControllerOption

WithControllerValidatorForceNone forces the controller to accept no validators. It is intended for testing purposes. It is highly recommended to use a validator to ensure data quality.

type CreateOption

type CreateOption func(*createOptions)

func WithCreateData

func WithCreateData(data []byte) CreateOption

func WithCreateObject

func WithCreateObject(object Objecter) CreateOption

type DeleteOption

type DeleteOption func(*deleteOptions)

func WithDeleteData

func WithDeleteData(data []byte) DeleteOption

func WithDeleteKey

func WithDeleteKey(key ObjectKeyer) DeleteOption

func WithDeleteObject

func WithDeleteObject(object Objecter) DeleteOption

type Error

type Error struct {
	// Status is the HTTP status code applicable to this problem.
	Status  int    `json:"status,omitempty"`
	Message string `json:"message,omitempty"`
}

func (*Error) Error

func (e *Error) Error() string

func (*Error) Is

func (e *Error) Is(err error) bool

type Event

type Event struct {
	Operation EventOperation
	Data      []byte
	Key       ObjectKeyer
	Reply     chan EventResult
}

func (Event) Respond

func (e Event) Respond(result EventResult) error

type EventOperation

type EventOperation string
const (
	// EventOperationPut indicates that the object has been created or updated.
	EventOperationPut EventOperation = "put"
	// EventOperationDelete indicates that the object has been marked for
	// deletion by setting the metadata.deletionTimestamp field.
	// It does not mean that the deleteionTimestamp has been reached yet,
	// so the deletionTimestamp may be in the future.
	EventOperationDelete EventOperation = "delete"
	// EventOperationPurge indicates that the object no longer exists in the kv
	// store.
	EventOperationPurge EventOperation = "purge"
)

type EventResult

type EventResult struct {
	Result Result
	Err    error
}

type Finalizers

type Finalizers []string

Finalizers are a way to prevent garbage collection of objects until a controller has finished some cleanup logic.

func (*Finalizers) Contains

func (f *Finalizers) Contains(finalizer string) bool

func (*Finalizers) String

func (f *Finalizers) String() string

type GenericObject

type GenericObject struct {
	TypeMeta   `json:",inline"`
	ObjectMeta `json:"metadata,omitempty"`

	Remaining map[string]json.RawMessage `json:"-"`
}

GenericObject represents a generic object, containing the type and object meta, and also a body. GenericObject does not care what the body is, but it stores it so that you can unmarshal objects as a GenericObject, perform operations on the metadata and marshal back to JSON with the full body.

If you only want to unmarshal and get the type or object meta, use MetaOnlyObject instead.

func (GenericObject) MarshalJSON

func (g GenericObject) MarshalJSON() ([]byte, error)

MarhsalJSON marshals the object to JSON.

func (*GenericObject) UnmarshalJSON

func (g *GenericObject) UnmarshalJSON(data []byte) error

type GenericObjectList

type GenericObjectList struct {
	Items []GenericObject `json:"items,omitempty"`
}

type GetOption

type GetOption func(*getOptions)

func WithGetKey

func WithGetKey(key ObjectKeyer) GetOption

type Info

type Info struct {
	Title       string `json:"title"`
	Description string `json:"description,omitempty"`
}

type LabelSelector

type LabelSelector struct {
	// MatchLabels is a map of key/value pairs, used to explicitly match labels
	// of an object.
	MatchLabels map[string]string `json:"matchLabels,omitempty" cue:",opt"`

	MatchExpressions []LabelSelectorRequirement `json:"matchExpressions,omitempty" cue:",opt"`
}

func (LabelSelector) Matches

func (s LabelSelector) Matches(labels map[string]string) bool

type LabelSelectorOperator

type LabelSelectorOperator string
const (
	LabelSelectorOpIn           LabelSelectorOperator = "In"
	LabelSelectorOpNotIn        LabelSelectorOperator = "NotIn"
	LabelSelectorOpExists       LabelSelectorOperator = "Exists"
	LabelSelectorOpDoesNotExist LabelSelectorOperator = "DoesNotExist"
)

type LabelSelectorRequirement

type LabelSelectorRequirement struct {
	Key      string                `json:"key" cue:""`
	Operator LabelSelectorOperator `json:"operator" cue:"\"In\" | \"NotIn\" | \"Exists\" | \"DoesNotExist\""`
	// Values must be non-nil for In or NotIn operators.
	// Otherwise the Values has no effect.
	Values []string `json:"values,omitempty" cue:",opt"`
}

type ListOption

type ListOption func(*listOption)

func WithListKey

func WithListKey(obj ObjectKeyer) ListOption

func WithListResponseGenericObjects

func WithListResponseGenericObjects(resp *GenericObjectList) ListOption

func WithListResponseWriter

func WithListResponseWriter(w io.Writer) ListOption

type MetaOnlyObject

type MetaOnlyObject struct {
	TypeMeta   `json:",inline"`
	ObjectMeta `json:"metadata"`
}

MetaOnlyObject is an object that has no spec or status. It is used for unmarshalling objects from the store to read metadata.

type NATSResponseWriter

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

func (*NATSResponseWriter) Flush

func (r *NATSResponseWriter) Flush()

Flush sends any buffered data to the client.

func (*NATSResponseWriter) Header

func (r *NATSResponseWriter) Header() http.Header

Header implements http.ResponseWriter.

func (*NATSResponseWriter) Write

func (r *NATSResponseWriter) Write(b []byte) (int, error)

Write implements http.ResponseWriter. It writes the bytes to an http.Response and sends it to the client.

func (*NATSResponseWriter) WriteHeader

func (r *NATSResponseWriter) WriteHeader(statusCode int)

WriteHeader implements http.ResponseWriter.

type ObjectClient

type ObjectClient[T Objecter] struct {
	Client Client
}

func (ObjectClient[T]) Apply

func (oc ObjectClient[T]) Apply(
	ctx context.Context,
	object T,
	opts ...ApplyOption,
) (ApplyOpResult, error)

func (ObjectClient[T]) Create

func (oc ObjectClient[T]) Create(
	ctx context.Context,
	object T,
) error

func (ObjectClient[T]) Delete

func (oc ObjectClient[T]) Delete(
	ctx context.Context,
	object T,
) error

func (ObjectClient[T]) Get

func (oc ObjectClient[T]) Get(
	ctx context.Context,
	opts ...GetOption,
) (T, error)

func (ObjectClient[T]) List

func (oc ObjectClient[T]) List(
	ctx context.Context,
	opts ...ListOption,
) ([]T, error)

func (ObjectClient[T]) Run

func (oc ObjectClient[T]) Run(
	ctx context.Context,
	actioner Actioner,
	object T,
	opts ...RunOption,
) (T, error)

func (ObjectClient[T]) Validate

func (oc ObjectClient[T]) Validate(
	ctx context.Context,
	object T,
) error

type ObjectKey

type ObjectKey struct {
	Group   string
	Version string
	Kind    string
	Account string
	Name    string
}

func ObjectKeyFromObject

func ObjectKeyFromObject(object Objecter) ObjectKey

func ObjectKeyFromString

func ObjectKeyFromString(key string) (ObjectKey, error)

func (ObjectKey) ObjectAccount

func (o ObjectKey) ObjectAccount() string

func (ObjectKey) ObjectGroup

func (o ObjectKey) ObjectGroup() string

func (ObjectKey) ObjectKind

func (o ObjectKey) ObjectKind() string

func (ObjectKey) ObjectName

func (o ObjectKey) ObjectName() string

func (ObjectKey) ObjectVersion

func (o ObjectKey) ObjectVersion() string

func (ObjectKey) String

func (o ObjectKey) String() string

type ObjectKeyer

type ObjectKeyer interface {
	ObjectGroup() string
	ObjectVersion() string
	ObjectKind() string
	ObjectAccount() string
	ObjectName() string
}

ObjectKeyer is an interface that can produce a unique key for an object.

type ObjectList

type ObjectList struct {
	Items []json.RawMessage `json:"items,omitempty"`
}

type ObjectMeta

type ObjectMeta struct {
	Name    string `json:"name,omitempty" cue:"=~\"^[a-zA-Z0-9-_]+$\""`
	Account string `json:"account,omitempty" cue:"=~\"^[a-zA-Z0-9-_]+$\""`

	Labels map[string]string `json:"labels,omitempty" cue:",opt"`

	// Revision is the revision number of the object.
	Revision          *uint64                     `json:"revision,omitempty" cue:",opt"`
	OwnerReferences   OwnerReferences             `json:"ownerReferences,omitempty" cue:",opt"`
	DeletionTimestamp *Time                       `json:"deletionTimestamp,omitempty" cue:",opt"`
	ManagedFields     managedfields.ManagedFields `json:"managedFields,omitempty" cue:",opt"`
	// Finalizers are a way for controllers to prevent garbage collection of
	// objects. The GC will not delete an object unless it has no finalizers.
	// Hence, it is the responsibility of the controller to remove the
	// finalizers once the object has been marked for deletion (by setting the
	// deletionTimestamp).
	//
	// Use type alias to "correctly" marshal to json.
	// A nil Finalizers is omitted from JSON.
	// A non-nil Finalizers is marshalled as an empty array if it is empty.
	Finalizers *Finalizers `json:"finalizers,omitempty" cue:",opt"`
}

func (ObjectMeta) ObjectAccount

func (o ObjectMeta) ObjectAccount() string

func (ObjectMeta) ObjectDeleteNow

func (o ObjectMeta) ObjectDeleteNow() bool

ObjectDeleteNow returns true if the object has a deletion timestamp that has expired, and the controller should therefore delete the object.

func (ObjectMeta) ObjectDeletionTimestamp

func (o ObjectMeta) ObjectDeletionTimestamp() *Time

func (ObjectMeta) ObjectManagedFields

func (o ObjectMeta) ObjectManagedFields() managedfields.ManagedFields

func (ObjectMeta) ObjectName

func (o ObjectMeta) ObjectName() string

func (ObjectMeta) ObjectOwnerReference

func (o ObjectMeta) ObjectOwnerReference(
	owner Objecter,
) (OwnerReference, bool)

func (ObjectMeta) ObjectOwnerReferences

func (o ObjectMeta) ObjectOwnerReferences() []OwnerReference

func (ObjectMeta) ObjectRevision

func (o ObjectMeta) ObjectRevision() *uint64

type Objecter

type Objecter interface {
	ObjectKeyer
	ObjectRevision() *uint64
	ObjectDeletionTimestamp() *Time
	ObjectOwnerReferences() []OwnerReference
	ObjectOwnerReference(Objecter) (OwnerReference, bool)
	ObjectManagedFields() managedfields.ManagedFields
}

Objecter is an interface that represents an object in the Horizon API.

type OwnerReference

type OwnerReference struct {
	Group   string `json:"group,omitempty" cue:""`
	Version string `json:"version,omitempty" cue:""`
	Kind    string `json:"kind,omitempty" cue:""`
	Account string `json:"account,omitempty" cue:""`
	Name    string `json:"name,omitempty" cue:""`
}

func OwnerReferenceFromObject

func OwnerReferenceFromObject(object Objecter) OwnerReference

func (OwnerReference) IsOwnedBy

func (o OwnerReference) IsOwnedBy(owner Objecter) bool

func (OwnerReference) ObjectAccount

func (o OwnerReference) ObjectAccount() string

func (OwnerReference) ObjectGroup

func (o OwnerReference) ObjectGroup() string

func (OwnerReference) ObjectKind

func (o OwnerReference) ObjectKind() string

func (OwnerReference) ObjectName

func (o OwnerReference) ObjectName() string

func (OwnerReference) ObjectVersion

func (o OwnerReference) ObjectVersion() string

type OwnerReferences

type OwnerReferences []OwnerReference

func (OwnerReferences) IsOwnedBy

func (o OwnerReferences) IsOwnedBy(obj Objecter) bool

type Portal

type Portal struct {
	ObjectMeta `json:"metadata,omitempty" cue:""`

	Spec   *PortalSpec   `json:"spec,omitempty" cue:""`
	Status *PortalStatus `json:"status,omitempty" cue:",opt"`
}

func (Portal) ObjectGroup

func (e Portal) ObjectGroup() string

func (Portal) ObjectKind

func (e Portal) ObjectKind() string

func (Portal) ObjectVersion

func (e Portal) ObjectVersion() string

type PortalHandler

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

PortalHandler is a NATS to HTTP proxy handler for a portal extension. It subscribes to NATS and proxies the requests to the given handler.

func StartPortal

func StartPortal(
	ctx context.Context,
	nc *nats.Conn,
	ext Portal,
	handler http.Handler,
) (*PortalHandler, error)

func (*PortalHandler) Start

func (e *PortalHandler) Start(ctx context.Context) error

Start registers the portal with Horizon so that it is available in the UI, and then subscribes to NATS to handle the requests.

func (*PortalHandler) Stop

func (e *PortalHandler) Stop() error

type PortalSpec

type PortalSpec struct {
	DisplayName string `json:"displayName,omitempty"`
	Icon        string `json:"icon,omitempty"`
}

type PortalStatus

type PortalStatus struct{}

type Properties

type Properties []Schema

func (Properties) Get

func (p Properties) Get(key string) (Schema, bool)

func (Properties) MarshalJSON

func (p Properties) MarshalJSON() ([]byte, error)

func (*Properties) UnmarshalJSON

func (p *Properties) UnmarshalJSON(b []byte) error

type Reconciler

type Reconciler interface {
	Reconcile(context.Context, Request) (Result, error)
}

type Request

type Request struct {
	// Key is the unique identifier of the object in the nats kv store.
	// It is the key of the object that is being reconciled.
	Key ObjectKeyer
}

type Result

type Result struct {
	// Requeue tells the Controller to requeue the reconcile key.  Defaults to
	// false.
	Requeue bool

	// RequeueAfter if greater than 0, tells the Controller to requeue the
	// reconcile key after the Duration. Implies that Requeue is true, there is
	// no need to set Requeue to true at the same time as RequeueAfter.
	RequeueAfter time.Duration
}

Result contains the result of a Reconciler invocation.

func (*Result) IsZero

func (r *Result) IsZero() bool

IsZero returns true if this result is empty.

type RunMsg

type RunMsg struct {
	Timeout       time.Duration   `json:"timeout,omitempty"`
	Data          json.RawMessage `json:"data,omitempty"`
	LabelSelector LabelSelector   `json:"labelSelector,omitempty"`
}

type RunOption

type RunOption func(*runOption)

func WithRunActioner

func WithRunActioner(action Actioner) RunOption

func WithRunData

func WithRunData(data []byte) RunOption

func WithRunLabelSelector

func WithRunLabelSelector(ls LabelSelector) RunOption

func WithRunObject

func WithRunObject(object Objecter) RunOption

func WithRunTimeout

func WithRunTimeout(timeout time.Duration) RunOption

type Schema

type Schema struct {
	Key        string      `json:"-"`
	Type       *SchemaType `json:"type,omitempty"`
	Required   []string    `json:"required,omitempty"`
	Properties Properties  `json:"properties,omitempty"`

	MultipleOf       *float64     `json:"multipleOf,omitempty"`
	Maximum          *float64     `json:"maximum,omitempty"`
	ExclusiveMaximum *bool        `json:"exclusiveMaximum,omitempty"`
	Minimum          *float64     `json:"minimum,omitempty"`
	ExclusiveMinimum *bool        `json:"exclusiveMinimum,omitempty"`
	MaxLength        *int64       `json:"maxLength,omitempty"`
	MinLength        *int64       `json:"minLength,omitempty"`
	Pattern          *string      `json:"pattern,omitempty"`
	MaxItems         *int64       `json:"maxItems,omitempty"`
	MinItems         *int64       `json:"minItems,omitempty"`
	UniqueItems      *bool        `json:"uniqueItems,omitempty"`
	MaxProperties    *int64       `json:"maxProperties,omitempty"`
	MinProperties    *int64       `json:"minProperties,omitempty"`
	Enum             []string     `json:"enum,omitempty"`
	Not              *Schema      `json:"not,omitempty"`
	AllOf            []Schema     `json:"allOf,omitempty"`
	OneOf            []Schema     `json:"oneOf,omitempty"`
	AnyOf            []Schema     `json:"anyOf,omitempty"`
	Items            *Schema      `json:"items,omitempty"`
	Description      *string      `json:"description,omitempty"`
	Format           *string      `json:"format,omitempty"`
	Default          *interface{} `json:"default,omitempty"`
	Nullable         *bool        `json:"nullable,omitempty"`
	ReadOnly         *bool        `json:"readOnly,omitempty"`
	WriteOnly        *bool        `json:"writeOnly,omitempty"`
	Example          *interface{} `json:"example,omitempty"`
	Deprecated       *bool        `json:"deprecated,omitempty"`
}

func (Schema) Property

func (s Schema) Property(key string) (Schema, bool)

type SchemaType

type SchemaType string

type Spec

type Spec struct {
	Openapi    string     `json:"openapi"`
	Info       Info       `json:"info"` // Required.
	Components Components `json:"components,omitempty"`
}

func OpenAPISpecFromObject

func OpenAPISpecFromObject(obj Objecter) (*Spec, error)

func (Spec) Schema

func (s Spec) Schema() (Schema, error)

type Time

type Time struct {
	time.Time
}

func (*Time) IsPast

func (t *Time) IsPast() bool

type TypeMeta

type TypeMeta struct {
	APIVersion string `json:"apiVersion,omitempty"`
	Kind       string `json:"kind,omitempty"`
}

func (TypeMeta) ObjectGroup

func (t TypeMeta) ObjectGroup() string

func (TypeMeta) ObjectKind

func (t TypeMeta) ObjectKind() string

func (TypeMeta) ObjectVersion

func (t TypeMeta) ObjectVersion() string

type TypedObjectList

type TypedObjectList[T Objecter] struct {
	Items []T `json:"items,omitempty"`
}

type ValidateOption

type ValidateOption func(*validateOptions)

func WithValidateData

func WithValidateData(data []byte) ValidateOption

func WithValidateObject

func WithValidateObject(obj Objecter) ValidateOption

type Validator

type Validator interface {
	ValidateCreate(ctx context.Context, data []byte) error
	ValidateUpdate(ctx context.Context, old, data []byte) error
	ValidateDelete(ctx context.Context, data []byte) error
}

type Watcher

type Watcher struct {
	Conn *nats.Conn

	Init chan struct{}
	// contains filtered or unexported fields
}

func StartWatcher

func StartWatcher(
	ctx context.Context,
	conn *nats.Conn,
	opts ...WatcherOption,
) (*Watcher, error)

func (*Watcher) Close

func (w *Watcher) Close()

func (*Watcher) Start

func (w *Watcher) Start(ctx context.Context, opts ...WatcherOption) error

func (*Watcher) WaitUntilInit

func (w *Watcher) WaitUntilInit()

type WatcherOption

type WatcherOption func(*watcherOptions)

func WithWatcherCh

func WithWatcherCh(ch chan Event) WatcherOption

func WithWatcherDurable

func WithWatcherDurable(name string) WatcherOption

WithWatcherDurable sets the durable name for the nats consumer. In short, if you want to "load balance" the watcher across multiple instances, you can set the durable name to the same value for each. If you want each instance of the watcher to be completely independent, do not set the durable name of the consumer.

Read more about consumers: https://docs.nats.io/nats-concepts/jetstream/consumers

func WithWatcherFn

func WithWatcherFn(
	fn func(event Event) (Result, error),
) WatcherOption

func WithWatcherFor

func WithWatcherFor(obj ObjectKeyer) WatcherOption

func WithWatcherFromNow

func WithWatcherFromNow() WatcherOption

type ZeroValidator

type ZeroValidator struct{}

func (*ZeroValidator) ValidateCreate

func (z *ZeroValidator) ValidateCreate(ctx context.Context, data []byte) error

func (*ZeroValidator) ValidateDelete

func (z *ZeroValidator) ValidateDelete(ctx context.Context, data []byte) error

func (*ZeroValidator) ValidateUpdate

func (z *ZeroValidator) ValidateUpdate(
	ctx context.Context,
	old []byte,
	data []byte,
) error

Jump to

Keyboard shortcuts

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