Files
archie/internal/infrastructure/controlplanestore/operational_settings.go
T
sam 9d8f364af1
Quality / check (push) Successful in 5m53s
deploy / gate (push) Canceled after 0s
deploy / archied-image (push) Canceled after 0s
deploy / agent-image (push) Canceled after 0s
deploy / dist-zip (push) Canceled after 0s
feat(releaseupdate): signed OCI distribution sources for releases and the catalogue (#1715)
2026-10-31 18:18:43 +11:00

190 lines
8.7 KiB
Go

package controlplanestore
import (
"encoding/json"
"fmt"
"strings"
"time"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workintake"
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
"github.com/samcharles93/archie-core/internal/releaseupdate"
)
const (
RepositoryPoliciesKind = "repository-policies"
SchedulingPolicyKind = "scheduling-policy"
ToolSettingsKind = "tool-settings"
PluginSettingsKind = "plugin-settings"
ContainerRuntimePoliciesKind = "container-runtime-policies"
ExtensionSettingsKind = controlplanerpc.ExtensionSettingsKind
UpdateSettingsKind = controlplanerpc.UpdateSettingsKind
)
type schedulingPolicy struct {
PollInterval string `json:"poll_interval"`
MaxRetries int `json:"max_retries"`
// Label is the dispatch trigger label. Nil keeps the file's label.
Label *string `json:"label,omitempty"`
Dispatch config.Dispatch `json:"dispatch"`
}
type pluginSettings struct {
SkillsDir string `json:"skills_dir"`
}
func operationalDefinitions() []Definition {
return []Definition{
{Kind: RepositoryPoliciesKind, Title: "Repository policies", ApplyMode: "live", Document: []config.Repo{}, Seed: func(cfg config.Config) any { return append([]config.Repo{}, cfg.Repos...) }, Validate: validateRepositories},
// Restart-required: the Messaging Service, which owns the channel
// transports, reconciles them live and archied re-layers each update, but
// the Gateway's chat surfaces (workspace tools, rate limit, model
// catalogs) are boot-built, so a change cannot promise live apply
// everywhere the record reports it.
{Kind: ChannelSettingsKind, Title: "Channel settings", ApplyMode: "restart-required", Document: channelSettings{}, Seed: seedChannels, Validate: validateChannels, Normalize: normalizeChannels},
{Kind: SchedulingPolicyKind, Title: "Scheduling policy", ApplyMode: "live", Document: schedulingPolicy{}, Seed: func(cfg config.Config) any {
return schedulingPolicy{PollInterval: cfg.PollInterval.Std().String(), MaxRetries: cfg.MaxRetries, Label: &cfg.Label, Dispatch: cfg.Dispatch}
}, Validate: validateScheduling},
// Live: changed MCP servers are reconnected, rolling back to the old engine
// if the new one fails to start.
{Kind: ToolSettingsKind, Title: "Tool and MCP settings", ApplyMode: "live", Document: toolSettings{}, Seed: seedTools, Validate: validateTools},
// Restart-required: the one field, skills_dir, is read at boot, and the
// watch refuses a change rather than layering it into the running config
// while the boot-built consumers hold the old value
// (refuseSkillsDirChange).
{Kind: PluginSettingsKind, Title: "Plugin settings", ApplyMode: "restart-required", Document: pluginSettings{}, Seed: func(cfg config.Config) any {
return pluginSettings{cfg.SkillsDir}
}, Validate: validatePluginSettings},
// Live: each process that supervises extensions re-reads this on its sync
// tick, then starts, restarts or stops what changed.
{Kind: ExtensionSettingsKind, Title: "Extension settings", ApplyMode: "live", Document: controlplanerpc.ExtensionSettings{}, Seed: func(cfg config.Config) any {
return controlplanerpc.ExtensionSettings{CatalogueSource: cfg.Distribution.Catalogue, CatalogueKey: cfg.Distribution.CatalogueKey}
}, Validate: validateExtensions},
// Live: the container pool reads these on every acquire and the dispatcher
// is resized on publish.
// Live: every check and install reads the channel afresh.
{Kind: UpdateSettingsKind, Title: "Update settings", ApplyMode: "live", Document: controlplanerpc.UpdateSettings{}, Seed: func(cfg config.Config) any {
return controlplanerpc.UpdateSettings{Channel: "stable", Source: cfg.Distribution.Releases, Key: cfg.Distribution.ReleasesKey}
}, Validate: validateUpdateSettings},
{Kind: ContainerRuntimePoliciesKind, Title: "Container runtime policies", ApplyMode: "live", Document: containerRuntimePolicies{}, Seed: seedContainerPolicies, Validate: validateContainers, Normalize: normalizeContainerPolicies},
// Live: the retention sweep reads the document on every tick, so a
// change applies to the next sweep without a restart.
auditRetentionDefinition(),
// Live: the scheduler reads the zone on every claim and the State Store
// reads the retention on every sweep.
scheduleSettingsDefinition(),
}
}
// validateExtensions refuses a blank or repeated extension name: the name is
// the installed package the setting enables.
func validateExtensions(input []byte) error {
return validateAs(input, func(doc controlplanerpc.ExtensionSettings) error {
seen := make(map[string]struct{}, len(doc.Extensions))
for _, setting := range doc.Extensions {
if strings.TrimSpace(setting.Name) == "" {
return fmt.Errorf("extension name is required")
}
if _, dup := seen[setting.Name]; dup {
return fmt.Errorf("extension %q is listed twice", setting.Name)
}
seen[setting.Name] = struct{}{}
}
_, err := doc.Catalogue()
return err
})
}
// validatePluginSettings accepts every value.
func validatePluginSettings(input []byte) error {
return validateAs(input, func(pluginSettings) error { return nil })
}
func validateRepositories(input []byte) error {
// The rules live in the configuration package and are shared with the file
// document's own validation (configuration.ValidateRepositories): which
// repository lists are valid cannot differ between the file that seeds this
// resource and the resource that replaces it.
return validateAs(input, configuration.ValidateRepositories)
}
// validateScheduling applies the rules every org's document shares. The
// instance-wide fields are required of the system org and refused of every
// other (checkSchedulingWrite).
func validateScheduling(input []byte) error {
return validateAs(input, func(policy schedulingPolicy) error {
if policy.MaxRetries < 0 {
return fmt.Errorf("max_retries must not be negative")
}
if policy.PollInterval != "" {
interval, err := time.ParseDuration(policy.PollInterval)
if err != nil || interval <= 0 {
return fmt.Errorf("poll_interval must be a positive duration")
}
}
if policy.Dispatch.Trigger != "" && !configuration.DispatchTriggerValid(policy.Dispatch.Trigger) {
return fmt.Errorf("dispatch.trigger %q is not a discovery rule the daemon can poll with", policy.Dispatch.Trigger)
}
// A label-requiring trigger needs a label.
if workintake.RequiresLabel(policy.Dispatch.Trigger) && (policy.Label == nil || *policy.Label == "") {
return fmt.Errorf("label is required when dispatch.trigger is %q (an empty label matches every open issue)", policy.Dispatch.Trigger)
}
return nil
})
}
// checkSchedulingWrite separates the instance's polling from an org's
// discovery rule. The poll interval and retry cap belong to the one daemon
// (RuntimeConfig layers them from the system org), so another org's copy
// would parse and never apply; the system org's must still be complete,
// because the daemon refuses to start without them.
func checkSchedulingWrite(orgID string, value []byte) error {
var policy schedulingPolicy
if err := json.Unmarshal(value, &policy); err != nil {
return err
}
if orgID == storecontract.DefaultOrgID {
if policy.PollInterval == "" || policy.Dispatch.Trigger == "" {
return fmt.Errorf("%w: poll_interval and dispatch.trigger are required", ErrValidation)
}
return nil
}
if policy.PollInterval != "" || policy.MaxRetries != 0 {
return fmt.Errorf("%w: poll_interval and max_retries are instance settings; an org sets the dispatch rule and label only", ErrValidation)
}
return nil
}
// ApplyOrgScheduling returns cfg with an org's discovery rule over the
// instance's: a field the org leaves unset keeps the instance value, so an
// org that has written nothing polls as it always has.
func ApplyOrgScheduling(cfg config.Config, stored []byte) (config.Config, error) {
var policy schedulingPolicy
if err := json.Unmarshal(stored, &policy); err != nil {
return config.Config{}, fmt.Errorf("decode %s: %w", SchedulingPolicyKind, err)
}
if policy.Dispatch.Trigger != "" {
cfg.Dispatch.Trigger = policy.Dispatch.Trigger
}
if policy.Dispatch.AckReaction != "" {
cfg.Dispatch.AckReaction = policy.Dispatch.AckReaction
}
if policy.Label != nil {
cfg.Label = *policy.Label
}
return cfg, nil
}
// validateUpdateSettings refuses a channel the update scripts cannot select.
func validateUpdateSettings(input []byte) error {
return validateAs(input, func(doc controlplanerpc.UpdateSettings) error {
if _, err := doc.Releases(); err != nil {
return err
}
return releaseupdate.ValidateChannel(doc.Channel, doc.Pin)
})
}