297 lines
11 KiB
Go
297 lines
11 KiB
Go
package archiemessaging
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log/slog"
|
|
"maps"
|
|
"path/filepath"
|
|
"slices"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/samcharles93/archie-core/internal/app/servicekit"
|
|
"github.com/samcharles93/archie-core/internal/channels"
|
|
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
|
"github.com/samcharles93/archie-core/internal/domain/storepkg"
|
|
"github.com/samcharles93/archie-core/internal/infrastructure/channelext"
|
|
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
|
|
"github.com/samcharles93/archie-core/internal/infrastructure/extension"
|
|
"github.com/samcharles93/archie-core/internal/secret"
|
|
)
|
|
|
|
// refSuffix marks a setting that holds an "engine:key" secret reference.
|
|
const refSuffix = "_ref"
|
|
|
|
// telegramChannel is the package name the Telegram channel extension installs
|
|
// under.
|
|
const telegramChannel = "telegram"
|
|
|
|
// channelFactory builds extension channel instances on demand, so channels
|
|
// composed after startup (an org's own bot) are built exactly like the ones
|
|
// opened at startup.
|
|
type channelFactory struct {
|
|
host *extension.Host
|
|
source extension.Source
|
|
cacheDir string
|
|
secrets *secret.Registry
|
|
}
|
|
|
|
// build launches the channel package pkg as a channel named name, with the
|
|
// given settings.
|
|
func (f *channelFactory) build(ctx context.Context, pkg storepkg.Installed, file, name string, settings map[string]string) (channels.Channel, error) {
|
|
if f == nil {
|
|
return nil, fmt.Errorf("channel extensions are unavailable")
|
|
}
|
|
return buildExtensionChannel(ctx, f.host, f.source, f.cacheDir, pkg, file, name, settings, f.secrets)
|
|
}
|
|
|
|
// channelPackage finds an installed channel package by name and the binary it
|
|
// contributes on the channel surface.
|
|
func (f *channelFactory) channelPackage(ctx context.Context, name string) (storepkg.Installed, string, bool) {
|
|
if f == nil {
|
|
return storepkg.Installed{}, "", false
|
|
}
|
|
installed, err := f.source.Packages.ListInstalled(ctx)
|
|
if err != nil {
|
|
return storepkg.Installed{}, "", false
|
|
}
|
|
for _, pkg := range installed {
|
|
if pkg.Name != name || pkg.AcceptedAuthority == nil {
|
|
continue
|
|
}
|
|
index := slices.IndexFunc(pkg.Descriptor.Contributes.Extensions, func(x storepkg.Extension) bool { return x.Surface == storepkg.SurfaceChannel })
|
|
if index < 0 {
|
|
continue
|
|
}
|
|
return pkg, pkg.Descriptor.Contributes.Extensions[index].Path, true
|
|
}
|
|
return storepkg.Installed{}, "", false
|
|
}
|
|
|
|
// extensionPlan is one channel extension as the extension settings and the
|
|
// installed packages currently resolve it. A plan with needs set is enabled but
|
|
// cannot start.
|
|
type extensionPlan struct {
|
|
name string
|
|
pkg storepkg.Installed
|
|
file string
|
|
settings map[string]string
|
|
needs string
|
|
}
|
|
|
|
// same reports whether next needs no rebuild of the running channel.
|
|
func (p extensionPlan) same(next extensionPlan) bool {
|
|
return p.needs == next.needs && p.pkg.Digest == next.pkg.Digest && maps.Equal(p.settings, next.settings)
|
|
}
|
|
|
|
// planExtensionChannels resolves each enabled channel package to a plan, keyed
|
|
// by name. A package that is not installed, not accepted, or not enabled has no
|
|
// plan, which is what a disabled channel is.
|
|
func planExtensionChannels(ctx context.Context, log *slog.Logger, source extension.Source) (map[string]extensionPlan, error) {
|
|
settings, _, err := source.Enabled(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
installed, err := source.Packages.ListInstalled(ctx)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("list installed packages: %w", err)
|
|
}
|
|
plans := map[string]extensionPlan{}
|
|
for _, pkg := range installed {
|
|
setting, ok := settings[pkg.Name]
|
|
if !ok || !setting.Enabled || pkg.AcceptedAuthority == nil {
|
|
continue
|
|
}
|
|
index := slices.IndexFunc(pkg.Descriptor.Contributes.Extensions, func(x storepkg.Extension) bool { return x.Surface == storepkg.SurfaceChannel })
|
|
if index < 0 {
|
|
continue
|
|
}
|
|
plan := extensionPlan{name: pkg.Name, pkg: pkg, file: pkg.Descriptor.Contributes.Extensions[index].Path, settings: setting.Settings}
|
|
if missing := pkg.Descriptor.MissingSettings(setting.Settings); len(missing) > 0 {
|
|
plan.needs = "Missing " + strings.Join(missing, ", ")
|
|
log.WarnContext(ctx, "channel extension not started: required settings missing", "channel", pkg.Name, "missing", missing)
|
|
}
|
|
plans[pkg.Name] = plan
|
|
}
|
|
if setting := settings[telegramChannel]; setting.Enabled && !slices.ContainsFunc(installed, func(pkg storepkg.Installed) bool { return pkg.Name == telegramChannel }) {
|
|
// Report it as a channel, so the dashboard shows why the enabled
|
|
// bot is not running instead of showing nothing.
|
|
log.WarnContext(ctx, "telegram is enabled but its channel extension is not installed")
|
|
plans[telegramChannel] = extensionPlan{name: telegramChannel, needs: "The Telegram channel extension is not installed"}
|
|
}
|
|
return plans, nil
|
|
}
|
|
|
|
// buildPlan launches the channel a plan describes; a plan that needs something
|
|
// has no channel. The host passes the telegram channel the show_tool_calls
|
|
// session default.
|
|
func (f *channelFactory) buildPlan(ctx context.Context, plan extensionPlan, showToolCalls bool) (channels.Channel, error) {
|
|
if plan.needs != "" {
|
|
return nil, nil
|
|
}
|
|
values := plan.settings
|
|
if plan.name == telegramChannel {
|
|
values = maps.Clone(values)
|
|
if values == nil {
|
|
values = map[string]string{}
|
|
}
|
|
values["show_tool_calls"] = strconv.FormatBool(showToolCalls)
|
|
}
|
|
return f.build(ctx, plan.pkg, plan.file, plan.name, values)
|
|
}
|
|
|
|
// openExtensionChannels builds a channel for each installed channel package
|
|
// whose authority is accepted and that extension-settings enables. Later
|
|
// changes to the set are applied by syncExtensionChannels. Running extensions
|
|
// stop with ctx.
|
|
func openExtensionChannels(ctx context.Context, source extension.Source, secrets *secret.Registry, log *slog.Logger, showToolCalls bool) ([]*channelInstance, *channelFactory) {
|
|
cache, err := configuration.DefaultCacheDir()
|
|
if err != nil {
|
|
log.WarnContext(ctx, "channel extensions unavailable: no cache directory", "err", err)
|
|
return nil, nil
|
|
}
|
|
plans, err := planExtensionChannels(ctx, log, source)
|
|
if err != nil {
|
|
log.WarnContext(ctx, "channel extensions unavailable", "err", err)
|
|
return nil, nil
|
|
}
|
|
host := extension.NewHost(log)
|
|
factory := &channelFactory{host: host, source: source, cacheDir: filepath.Join(cache, "extensions", "channels"), secrets: secrets}
|
|
var instances []*channelInstance
|
|
for _, name := range slices.Sorted(maps.Keys(plans)) {
|
|
plan := plans[name]
|
|
ch, err := factory.buildPlan(ctx, plan, showToolCalls)
|
|
if err != nil {
|
|
log.WarnContext(ctx, "channel extension not started", "channel", name, "err", err)
|
|
continue
|
|
}
|
|
instances = append(instances, &channelInstance{name: name, channel: ch, needs: plan.needs, extension: &plan})
|
|
}
|
|
go func() {
|
|
<-ctx.Done()
|
|
host.Close()
|
|
}()
|
|
return instances, factory
|
|
}
|
|
|
|
// extensionChannelLoop applies changes to the extension settings and installed
|
|
// packages to the running channels until ctx ends.
|
|
func (s *Service) extensionChannelLoop(ctx context.Context) {
|
|
ticker := time.NewTicker(s.reconcileInterval)
|
|
defer ticker.Stop()
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-ticker.C:
|
|
if err := s.syncExtensionChannels(ctx); err != nil {
|
|
s.log.WarnContext(ctx, "channel extensions not synced", "err", err)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// syncExtensionChannels starts, replaces or stops each instance-level channel
|
|
// extension to match its plan. A channel that no longer has a plan is stopped
|
|
// but keeps its supervisor, so enabling it again starts it without a restart.
|
|
func (s *Service) syncExtensionChannels(ctx context.Context) error {
|
|
plans, err := planExtensionChannels(ctx, s.log, s.extensions.source)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
show := s.currentConfig().ShowToolCalls
|
|
for _, name := range slices.Sorted(maps.Keys(plans)) {
|
|
s.applyExtensionPlan(ctx, plans[name], show)
|
|
}
|
|
for _, instance := range s.instances() {
|
|
if _, still := plans[instance.name]; still || instance.owner != storecontract.DefaultOrgID || instance.currentExtension() == nil {
|
|
continue
|
|
}
|
|
instance.setExtension(nil, "")
|
|
if err := s.setChannelState(instance, nil); err != nil {
|
|
s.log.WarnContext(ctx, "channel extension not stopped", "channel", instance.name, "err", err)
|
|
continue
|
|
}
|
|
s.status.Declare(instance.name, false, false)
|
|
}
|
|
s.signalPublish()
|
|
return nil
|
|
}
|
|
|
|
func (s *Service) applyExtensionPlan(ctx context.Context, plan extensionPlan, show bool) {
|
|
instance := s.systemInstance(plan.name)
|
|
if instance != nil {
|
|
if previous := instance.currentExtension(); previous != nil && previous.same(plan) {
|
|
return
|
|
}
|
|
}
|
|
ch, err := s.extensions.buildPlan(ctx, plan, show)
|
|
if err != nil {
|
|
s.log.WarnContext(ctx, "channel extension not started", "channel", plan.name, "err", err)
|
|
return
|
|
}
|
|
if instance == nil {
|
|
instance = &channelInstance{name: plan.name, kind: plan.name, owner: storecontract.DefaultOrgID, channel: ch, needs: plan.needs, extension: &plan, notify: make(chan struct{}, 1)}
|
|
s.addChannel(ctx, instance)
|
|
return
|
|
}
|
|
instance.setExtension(&plan, plan.needs)
|
|
if err := s.setChannelState(instance, ch); err != nil {
|
|
s.log.WarnContext(ctx, "channel extension not restarted", "channel", plan.name, "err", err)
|
|
return
|
|
}
|
|
s.status.Declare(instance.name, ch != nil, channelReloadable(ch))
|
|
}
|
|
|
|
// systemInstance finds the instance-level channel of that name; an org's
|
|
// channel of the same kind is a different instance.
|
|
func (s *Service) systemInstance(name string) *channelInstance {
|
|
for _, instance := range s.instances() {
|
|
if instance.name == name && instance.owner == storecontract.DefaultOrgID {
|
|
return instance
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (c *channelInstance) currentExtension() *extensionPlan {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
return c.extension
|
|
}
|
|
|
|
func (c *channelInstance) setExtension(plan *extensionPlan, needs string) {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
c.extension, c.needs = plan, needs
|
|
}
|
|
|
|
func buildExtensionChannel(ctx context.Context, host *extension.Host, source extension.Source, cacheDir string, pkg storepkg.Installed, file, name string, settings map[string]string, secrets *secret.Registry) (channels.Channel, error) {
|
|
binary, sum, err := extension.Materialize(ctx, source.Packages, cacheDir, pkg, file)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
plain := make(map[string]string, len(settings))
|
|
resolved := make(map[string]string)
|
|
for key, value := range settings {
|
|
base, isRef := strings.CutSuffix(key, refSuffix)
|
|
if !isRef {
|
|
plain[key] = value
|
|
continue
|
|
}
|
|
engine, ref, ok := strings.Cut(value, ":")
|
|
if !ok {
|
|
return nil, fmt.Errorf("setting %q: want engine:key", key)
|
|
}
|
|
secretValue, err := secrets.Resolve(secret.SecretRef{Engine: engine, Key: ref})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("setting %q: %w", key, err)
|
|
}
|
|
resolved[base] = secretValue
|
|
}
|
|
spec := extension.Spec{Name: "channel/" + name, Path: binary, SHA256: sum, Env: slices.Clone(pkg.AcceptedAuthority.Env), Egress: slices.Clone(pkg.AcceptedAuthority.EgressHosts)}
|
|
return channelext.New(host, name, spec, plain, resolved, servicekit.ServerLimits()), nil
|
|
}
|