Files
archie/internal/app/archiemessaging/enablement_test.go
T
sam 1ea15462c0
Quality / check (push) Successful in 4m56s
deploy / gate (push) Successful in 6m11s
deploy / archied-image (push) Successful in 2m56s
deploy / agent-image (push) Successful in 10s
deploy / dist-zip (push) Skipped
feat(messaging): run Telegram as an archipelago channel extension (#1399)
The bundled internal/channels/telegram package (17 files) is deleted; the
channel now ships as archipelago/channels/telegram, launched by archiemessaging
through the existing channel-extension machinery. An existing [chat.telegram]
config enables it with the same keys: the token stays a secret reference
(token_ref) the host resolves, allowed_user_ids and show_tool_calls map onto
extension settings. Per-org bots compose the same extension per org from the
org's credential binding. Reload support is now derived from a channels.Reloader
interface instead of a *telegram.Gateway assertion. The five host-only seams
(/update, release announcements, running versions, in-place show_tool_calls,
reload) are dropped from the channel and need a contract home or deletion.
2026-10-31 18:19:21 +11:00

248 lines
7.3 KiB
Go

package archiemessaging
import (
"context"
"encoding/json"
"log/slog"
"sync"
"testing"
"time"
"github.com/samcharles93/archie-core/internal/channels"
"github.com/samcharles93/archie-core/internal/channels/status"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/messaging"
"github.com/samcharles93/archie-core/internal/secret"
)
// servingChannel reports itself running once it starts, which is what an
// enable is reported active on: a channel that only reaches "starting" is not
// serving yet.
type servingChannel struct {
mu sync.Mutex
starts int
show bool
}
func (c *servingChannel) Name() string { return "test" }
func (c *servingChannel) Start(ctx context.Context, _ messaging.ChatContract, lifecycle channels.Lifecycle) error {
c.mu.Lock()
c.starts++
c.mu.Unlock()
if lifecycle.Starting != nil {
lifecycle.Starting()
}
if lifecycle.Running != nil {
lifecycle.Running()
}
<-ctx.Done()
return nil
}
func (c *servingChannel) Stop(context.Context) error { return nil }
func (c *servingChannel) ConfigSchema() json.RawMessage { return nil }
func (c *servingChannel) ValidateConfig(map[string]any) error { return nil }
func (c *servingChannel) SetShowToolCalls(show bool) {
c.mu.Lock()
defer c.mu.Unlock()
c.show = show
}
func (c *servingChannel) count() int {
c.mu.Lock()
defer c.mu.Unlock()
return c.starts
}
func (c *servingChannel) showToolCalls() bool {
c.mu.Lock()
defer c.mu.Unlock()
return c.show
}
// startTestService composes a service and adds one scripted channel instance
// under supervision, so enablement can be driven without a real channel.
func startTestService(t *testing.T, ch *servingChannel) *Service {
t.Helper()
srv, err := compose(context.Background(), deps{Log: slog.Default()})
if err != nil {
t.Fatalf("compose: %v", err)
}
inst := &channelInstance{
name: "test", kind: "test",
rebuild: func(ResolvedConfig) (channels.Channel, error) { return ch, nil },
notify: make(chan struct{}, 1),
}
srv.retry = channelRetryPolicy{attempts: 3, backoff: time.Millisecond, maxBackoff: time.Millisecond}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() {
defer close(done)
_ = srv.Start(ctx)
}()
t.Cleanup(func() {
cancel()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Error("service did not stop after cancel")
}
})
srv.addChannel(ctx, inst)
waitSupervised(t, srv, "test")
return srv
}
// waitSupervised blocks until the channel's supervisor exists, so an enable
// issued right after Start is not refused for racing it.
func waitSupervised(t *testing.T, srv *Service, id string) {
t.Helper()
deadline := time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) {
inst := srv.instanceByID(id)
inst.mu.Lock()
supervised := inst.supervised
inst.mu.Unlock()
if supervised {
return
}
time.Sleep(time.Millisecond)
}
t.Fatalf("channel %q was never supervised", id)
}
func channelByID(t *testing.T, srv *Service, id string) status.Status {
t.Helper()
for _, st := range srv.ChannelStatus() {
if st.ID == id {
return st
}
}
t.Fatalf("no channel %q in status", id)
return status.Status{}
}
// waitCount blocks until count reaches want, so an async start is observed
// rather than slept for.
func waitCount(t *testing.T, count func() int, want int) {
t.Helper()
deadline := time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) {
if count() >= want {
return
}
time.Sleep(time.Millisecond)
}
t.Fatalf("channel started %d times, want at least %d", count(), want)
}
// TestChannelEnableDisableLive pins that enabling and disabling a channel
// starts and stops it without a service restart, and that its declaration
// follows: a channel that was never configured is not reported as configured,
// and one that enablement stopped is reported stopped and unconfigured.
func TestChannelEnableDisableLive(t *testing.T) {
ch := &servingChannel{}
srv := startTestService(t, ch)
if before := channelByID(t, srv, "test"); before.Configured || before.State != status.StateStopped {
t.Fatalf("test before enable = %+v, want not configured and stopped", before)
}
if err := srv.enableChannel("test", ResolvedConfig{}); err != nil {
t.Fatalf("enable: %v", err)
}
waitCount(t, ch.count, 1)
if enabled := channelByID(t, srv, "test"); !enabled.Configured || enabled.State != status.StateRunning {
t.Fatalf("test after enable = %+v, want configured and running", enabled)
}
if err := srv.disableChannel("test"); err != nil {
t.Fatalf("disable: %v", err)
}
if disabled := channelByID(t, srv, "test"); disabled.Configured || disabled.State != status.StateStopped {
t.Fatalf("test after disable = %+v, want not configured and stopped", disabled)
}
}
// fakeSettings serves a stored chat config at a version, the way the
// control-plane client does.
type fakeSettings struct {
chat config.ChatConfig
version int64
}
func (f fakeSettings) RuntimeChatConfig(context.Context, config.ChatConfig) (config.ChatConfig, int64, error) {
return f.chat, f.version, nil
}
// TestReconcileAppliesShowToolCalls pins the live settings path that remains:
// a stored channel-settings version newer than the applied one reaches the
// running channels that accept show_tool_calls, and is recorded as applied.
func TestReconcileAppliesShowToolCalls(t *testing.T) {
ch := &servingChannel{}
srv := startTestService(t, ch)
if err := srv.enableChannel("test", ResolvedConfig{}); err != nil {
t.Fatalf("enable: %v", err)
}
waitCount(t, ch.count, 1)
srv.settingsSource = fakeSettings{
chat: config.ChatConfig{ShowToolCalls: true},
version: 1,
}
if err := srv.reconcileOnce(context.Background()); err != nil {
t.Fatalf("reconcile: %v", err)
}
if !ch.showToolCalls() {
t.Fatal("show_tool_calls was not applied to the running channel")
}
if srv.appliedVersion.Load() != 1 {
t.Fatalf("appliedVersion = %d, want 1", srv.appliedVersion.Load())
}
if srv.currentConfig().ShowToolCalls != true {
t.Fatal("running config does not carry the applied setting")
}
// An older version is a no-op.
srv.settingsSource = fakeSettings{version: 1}
if err := srv.reconcileOnce(context.Background()); err != nil {
t.Fatalf("reconcile stale: %v", err)
}
}
// TestTelegramFileSetting pins the mapping that keeps an existing
// [chat.telegram] file configuration working through the channel extension:
// the token stays a secret reference for the host to resolve, the allowlist
// joins the same way the extension parses it, and no token means no setting.
func TestTelegramFileSetting(t *testing.T) {
setting, ok := telegramFileSetting(config.TelegramConfig{
Token: secret.SecretRef{Engine: "env", Key: "ARCHIE_TELEGRAM_TOKEN"},
AllowedUserIDs: []int64{111, 222},
}, true)
if !ok {
t.Fatal("setting not produced for a configured token")
}
if setting.Name != "telegram" || !setting.Enabled {
t.Fatalf("setting = %+v, want name telegram enabled", setting)
}
want := map[string]string{
"token_ref": "env:ARCHIE_TELEGRAM_TOKEN",
"allowed_user_ids": "111,222",
"show_tool_calls": "true",
}
for key, value := range want {
if setting.Settings[key] != value {
t.Errorf("settings[%q] = %q, want %q", key, setting.Settings[key], value)
}
}
if _, ok := telegramFileSetting(config.TelegramConfig{}, false); ok {
t.Fatal("empty token produced a setting, want none")
}
}