bouncer/internal/setup/registry.go
William Petit 449fb69c02
Some checks are pending
Cadoles/bouncer/pipeline/pr-develop Build started...
Cadoles/bouncer/pipeline/head This commit looks good
feat: add layer definition api
2024-05-17 15:44:28 +02:00

90 lines
2.1 KiB
Go

package setup
import (
"context"
"forge.cadoles.com/cadoles/bouncer/internal/config"
"forge.cadoles.com/cadoles/bouncer/internal/proxy/director"
"forge.cadoles.com/cadoles/bouncer/internal/schema"
"forge.cadoles.com/cadoles/bouncer/internal/store"
"github.com/pkg/errors"
)
type layerEntry struct {
setup LayerSetupFunc
rawOptionsSchema []byte
}
type Registry struct {
layers map[store.LayerType]layerEntry
}
type LayerSetupFunc func(*config.Config) (director.Layer, error)
func (r *Registry) RegisterLayer(layerType store.LayerType, layerSetup LayerSetupFunc, rawOptionsSchema []byte) {
r.layers[layerType] = layerEntry{
setup: layerSetup,
rawOptionsSchema: rawOptionsSchema,
}
}
func (r *Registry) GetLayerOptionsRawSchema(layerType store.LayerType) ([]byte, error) {
layerEntry, exists := r.layers[layerType]
if !exists {
return nil, errors.WithStack(ErrNotFound)
}
return layerEntry.rawOptionsSchema, nil
}
func (r *Registry) GetLayerOptionsSchema(layerType store.LayerType) (*schema.Schema, error) {
rawSchema, err := r.GetLayerOptionsRawSchema(layerType)
if err != nil {
return nil, errors.WithStack(err)
}
schema, err := schema.Parse(rawSchema)
if err != nil {
return nil, errors.WithStack(err)
}
return schema, nil
}
func (r *Registry) GetLayers(ctx context.Context, conf *config.Config) ([]director.Layer, error) {
layers := make([]director.Layer, 0, len(r.layers))
for layerType, layerEntry := range r.layers {
layer, err := layerEntry.setup(conf)
if err != nil {
return nil, errors.Wrapf(err, "could not create layer '%s'", layerType)
}
layers = append(layers, layer)
}
return layers, nil
}
func (r *Registry) LayerTypeExists(layerType store.LayerType) bool {
_, exists := r.layers[layerType]
return exists
}
func (r *Registry) GetLayerTypes() []store.LayerType {
layerTypes := make([]store.LayerType, 0, len(r.layers))
for layerType := range r.layers {
layerTypes = append(layerTypes, layerType)
}
return layerTypes
}
func NewRegistry() *Registry {
return &Registry{
layers: make(map[store.LayerType]layerEntry),
}
}