feat(extensions): typed extension settings (number, boolean, duration, list, select)
This commit is contained in:
6 files changed
+180
-17
No files matched your search
@@ -41,6 +41,62 @@ type Setting struct {
|
||||
Description string `yaml:"description" json:"description,omitempty"`
|
||||
Secret bool `yaml:"secret" json:"secret,omitempty"`
|
||||
Required bool `yaml:"required" json:"required,omitempty"`
|
||||
// Type is how the value is entered and checked; empty means a string.
|
||||
Type string `yaml:"type" json:"type,omitempty"`
|
||||
// Options are the allowed values of a select setting.
|
||||
Options []string `yaml:"options" json:"options,omitempty"`
|
||||
}
|
||||
|
||||
// SettingType names how a setting's value is entered and validated.
|
||||
type SettingType string
|
||||
|
||||
// Setting types. The empty type is a string.
|
||||
const (
|
||||
SettingString SettingType = "string"
|
||||
SettingNumber SettingType = "number"
|
||||
SettingBoolean SettingType = "boolean"
|
||||
SettingDuration SettingType = "duration"
|
||||
SettingList SettingType = "list"
|
||||
SettingSelect SettingType = "select"
|
||||
)
|
||||
|
||||
// Kind returns the setting's type with the default applied.
|
||||
func (s Setting) Kind() SettingType {
|
||||
if s.Type == "" {
|
||||
return SettingString
|
||||
}
|
||||
return SettingType(s.Type)
|
||||
}
|
||||
|
||||
func (s Setting) validateType() error {
|
||||
switch s.Kind() {
|
||||
case SettingString, SettingNumber, SettingBoolean, SettingDuration, SettingList, SettingSelect:
|
||||
default:
|
||||
return fmt.Errorf("setting %q: unknown type %q", s.Key, s.Type)
|
||||
}
|
||||
if s.Secret && s.Kind() != SettingString {
|
||||
return fmt.Errorf("setting %q: a secret setting is a string", s.Key)
|
||||
}
|
||||
if s.Required && s.Kind() == SettingBoolean {
|
||||
return fmt.Errorf("setting %q: a boolean setting cannot be required, false counts as filled", s.Key)
|
||||
}
|
||||
if s.Kind() != SettingSelect {
|
||||
if len(s.Options) > 0 {
|
||||
return fmt.Errorf("setting %q: options belong to a select setting", s.Key)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if len(s.Options) == 0 {
|
||||
return fmt.Errorf("setting %q: a select setting needs options", s.Key)
|
||||
}
|
||||
seen := make(map[string]bool, len(s.Options))
|
||||
for _, option := range s.Options {
|
||||
if option == "" || seen[option] {
|
||||
return fmt.Errorf("setting %q: options must be non-empty and unique", s.Key)
|
||||
}
|
||||
seen[option] = true
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var settingKeyPattern = regexp.MustCompile(`^[a-z][a-z0-9_]*$`)
|
||||
@@ -69,6 +125,9 @@ func (d Descriptor) validateSettings() error {
|
||||
case setting.Secret != strings.HasSuffix(setting.Key, "_ref"):
|
||||
return fmt.Errorf("setting %q: a secret setting's key ends in _ref, and only a secret's does", setting.Key)
|
||||
}
|
||||
if err := setting.validateType(); err != nil {
|
||||
return err
|
||||
}
|
||||
seen[setting.Key] = true
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -8,7 +8,9 @@ import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storepkg"
|
||||
@@ -429,11 +431,49 @@ func declaredSettings(schema []storepkg.Setting, values map[string]string) (map[
|
||||
return nil, fmt.Errorf("%s must be a secret reference (engine:key)", setting.Label)
|
||||
}
|
||||
}
|
||||
value, err := typedSettingValue(setting, value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[key] = value
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// typedSettingValue checks a non-empty value against the setting's type and
|
||||
// returns its normalised form.
|
||||
func typedSettingValue(setting storepkg.Setting, value string) (string, error) {
|
||||
label := setting.Label
|
||||
switch setting.Kind() {
|
||||
case storepkg.SettingNumber:
|
||||
if _, err := strconv.ParseFloat(value, 64); err != nil {
|
||||
return "", fmt.Errorf("%s must be a number", label)
|
||||
}
|
||||
case storepkg.SettingBoolean:
|
||||
if value != "true" && value != "false" {
|
||||
return "", fmt.Errorf("%s must be true or false", label)
|
||||
}
|
||||
case storepkg.SettingDuration:
|
||||
if d, err := time.ParseDuration(value); err != nil || d <= 0 {
|
||||
return "", fmt.Errorf("%s must be a duration such as 30s", label)
|
||||
}
|
||||
case storepkg.SettingList:
|
||||
items := strings.Split(value, ",")
|
||||
for i, item := range items {
|
||||
items[i] = strings.TrimSpace(item)
|
||||
if items[i] == "" {
|
||||
return "", fmt.Errorf("%s must be a comma-separated list without empty items", label)
|
||||
}
|
||||
}
|
||||
return strings.Join(items, ","), nil
|
||||
case storepkg.SettingSelect:
|
||||
if !slices.Contains(setting.Options, value) {
|
||||
return "", fmt.Errorf("%s must be one of %s", label, strings.Join(setting.Options, ", "))
|
||||
}
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
// withSettings returns doc with the named extension's settings replaced,
|
||||
// keeping whether it is enabled.
|
||||
func withSettings(doc controlplanerpc.ExtensionSettings, name string, values map[string]string) controlplanerpc.ExtensionSettings {
|
||||
|
||||
@@ -13,6 +13,11 @@ func TestDeclaredSettings(t *testing.T) {
|
||||
schema := []storepkg.Setting{
|
||||
{Key: "imap_addr", Label: "IMAP address", Required: true},
|
||||
{Key: "password_ref", Label: "Password", Secret: true, Required: true},
|
||||
{Key: "ratio", Label: "Ratio", Type: "number"},
|
||||
{Key: "tls", Label: "Use TLS", Type: "boolean"},
|
||||
{Key: "poll", Label: "Poll interval", Type: "duration"},
|
||||
{Key: "folders", Label: "Folders", Type: "list"},
|
||||
{Key: "mode", Label: "Mode", Type: "select", Options: []string{"fast", "safe"}},
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -26,6 +31,17 @@ func TestDeclaredSettings(t *testing.T) {
|
||||
{name: "raw secret", give: map[string]string{"password_ref": "hunter2"}, wantErr: true},
|
||||
{name: "reference without a key", give: map[string]string{"password_ref": "bws:"}, wantErr: true},
|
||||
{name: "reference without an engine", give: map[string]string{"password_ref": ":mail"}, wantErr: true},
|
||||
{name: "number accepted", give: map[string]string{"ratio": "0.5"}, want: map[string]string{"ratio": "0.5"}},
|
||||
{name: "number refused", give: map[string]string{"ratio": "half"}, wantErr: true},
|
||||
{name: "boolean accepted", give: map[string]string{"tls": "false"}, want: map[string]string{"tls": "false"}},
|
||||
{name: "boolean refused", give: map[string]string{"tls": "yes"}, wantErr: true},
|
||||
{name: "duration accepted", give: map[string]string{"poll": "30s"}, want: map[string]string{"poll": "30s"}},
|
||||
{name: "duration unparsable", give: map[string]string{"poll": "soon"}, wantErr: true},
|
||||
{name: "duration not positive", give: map[string]string{"poll": "0s"}, wantErr: true},
|
||||
{name: "list is normalised", give: map[string]string{"folders": "INBOX , Sent,Archive"}, want: map[string]string{"folders": "INBOX,Sent,Archive"}},
|
||||
{name: "list with an empty item", give: map[string]string{"folders": "INBOX,,Sent"}, wantErr: true},
|
||||
{name: "select accepted", give: map[string]string{"mode": "safe"}, want: map[string]string{"mode": "safe"}},
|
||||
{name: "select refused", give: map[string]string{"mode": "reckless"}, wantErr: true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
|
||||
@@ -6,10 +6,9 @@ import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Field, FieldContent, FieldDescription, FieldGroup, FieldLabel } from "@/components/ui/field";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Section } from "@/components/ui/section";
|
||||
import { useExtensionsStore, type Extension } from "@/stores/extensions";
|
||||
import SecretRefField from "./SecretRefField.vue";
|
||||
import ExtensionSettingField from "./ExtensionSettingField.vue";
|
||||
|
||||
const props = defineProps<{
|
||||
extension: Extension;
|
||||
@@ -39,18 +38,11 @@ const missing = computed(() =>
|
||||
props.extension.settings_schema.filter((spec) => spec.required && !(draft.value[spec.key] ?? "").trim()).map((spec) => spec.label),
|
||||
);
|
||||
|
||||
function secretRef(key: string): { engine: string; key: string } {
|
||||
const [engine = "", ...rest] = (draft.value[key] ?? "").split(":");
|
||||
return { engine, key: rest.join(":") };
|
||||
}
|
||||
function setSecretRef(key: string, value: { engine: string; key: string }): void {
|
||||
draft.value = { ...draft.value, [key]: value.engine || value.key ? `${value.engine}:${value.key}` : "" };
|
||||
}
|
||||
function save(): void {
|
||||
void store.saveSettings(props.extension.name, draft.value);
|
||||
}
|
||||
function setValue(key: string, value: string | number): void {
|
||||
draft.value = { ...draft.value, [key]: String(value) };
|
||||
function setValue(key: string, value: string): void {
|
||||
draft.value = { ...draft.value, [key]: value };
|
||||
}
|
||||
|
||||
const badge = computed(() => {
|
||||
@@ -91,14 +83,10 @@ const problem = computed(() => (props.extension.enabled && props.status?.state !
|
||||
<FieldDescription v-if="spec.description">{{ spec.description }}</FieldDescription>
|
||||
</FieldContent>
|
||||
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
|
||||
<div v-if="spec.secret" :id="`${extension.name}-${spec.key}`" role="group" :aria-label="spec.label" class="contents">
|
||||
<SecretRefField :model-value="secretRef(spec.key)" :id-prefix="`${extension.name}-${spec.key}`" @update:model-value="(value) => setSecretRef(spec.key, value)" />
|
||||
</div>
|
||||
<Input
|
||||
v-else
|
||||
<ExtensionSettingField
|
||||
:id="`${extension.name}-${spec.key}`"
|
||||
:spec="spec"
|
||||
:model-value="draft[spec.key] ?? ''"
|
||||
class="max-w-md font-mono"
|
||||
@update:model-value="(value) => setValue(spec.key, value)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
|
||||
import { DurationInput } from "@/components/ui/duration-input";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { NumberField, NumberFieldContent, NumberFieldDecrement, NumberFieldIncrement, NumberFieldInput } from "@/components/ui/number-field";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { TagsInput, TagsInputInput, TagsInputItem, TagsInputItemDelete, TagsInputItemText } from "@/components/ui/tags-input";
|
||||
import type { ExtensionSettingSpec } from "@/stores/extensions";
|
||||
import OptionSelect from "@/workflows/OptionSelect.vue";
|
||||
import SecretRefField from "./SecretRefField.vue";
|
||||
|
||||
// One typed setting. Every type reads and writes the string the server stores.
|
||||
const props = defineProps<{ spec: ExtensionSettingSpec; id: string }>();
|
||||
const model = defineModel<string>({ required: true });
|
||||
|
||||
const secretRef = computed(() => {
|
||||
const [engine = "", ...rest] = model.value.split(":");
|
||||
return { engine, key: rest.join(":") };
|
||||
});
|
||||
function setSecretRef(value: { engine: string; key: string }): void {
|
||||
model.value = value.engine || value.key ? `${value.engine}:${value.key}` : "";
|
||||
}
|
||||
const number = computed(() => (model.value.trim() === "" || Number.isNaN(Number(model.value)) ? undefined : Number(model.value)));
|
||||
function setNumber(value: number | undefined): void {
|
||||
model.value = value === undefined || Number.isNaN(value) ? "" : String(value);
|
||||
}
|
||||
const items = computed(() => model.value.split(",").map((item) => item.trim()).filter(Boolean));
|
||||
const options = computed(() => (props.spec.options ?? []).map((value) => ({ value, label: value })));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="spec.secret" :id="id" role="group" :aria-label="spec.label" class="contents">
|
||||
<SecretRefField :model-value="secretRef" :id-prefix="id" @update:model-value="setSecretRef" />
|
||||
</div>
|
||||
<NumberField v-else-if="spec.type === 'number'" :id="id" :model-value="number" class="w-40" @update:model-value="setNumber">
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement />
|
||||
<NumberFieldInput class="font-mono" />
|
||||
<NumberFieldIncrement />
|
||||
</NumberFieldContent>
|
||||
</NumberField>
|
||||
<Switch v-else-if="spec.type === 'boolean'" :id="id" :model-value="model === 'true'" @update:model-value="(on) => (model = on ? 'true' : 'false')" />
|
||||
<DurationInput v-else-if="spec.type === 'duration'" :id="id" :model-value="model" @update:model-value="(value) => (model = value)" />
|
||||
<div v-else-if="spec.type === 'list'" :id="id" role="group" :aria-label="spec.label" class="contents">
|
||||
<TagsInput :model-value="items" class="font-mono" @update:model-value="(list) => (model = list.map(String).join(','))">
|
||||
<TagsInputItem v-for="item in items" :key="item" :value="item">
|
||||
<TagsInputItemText />
|
||||
<TagsInputItemDelete />
|
||||
</TagsInputItem>
|
||||
<TagsInputInput :aria-label="spec.label" />
|
||||
</TagsInput>
|
||||
</div>
|
||||
<OptionSelect v-else-if="spec.type === 'select'" :id="id" :model-value="model" :options="options" @update:model-value="(value) => (model = value)" />
|
||||
<Input v-else :id="id" v-model="model" class="max-w-md font-mono" />
|
||||
</template>
|
||||
@@ -37,6 +37,10 @@ export interface ExtensionSettingSpec {
|
||||
description?: string;
|
||||
secret?: boolean;
|
||||
required?: boolean;
|
||||
/** Absent means string. */
|
||||
type?: "string" | "number" | "boolean" | "duration" | "list" | "select";
|
||||
/** Choices for a select. */
|
||||
options?: string[];
|
||||
}
|
||||
|
||||
/** A package the verified catalogue offers. */
|
||||
|
||||
Reference in new issue
Block a user