fix(archiemessaging): apply channel enablement live
This commit is contained in:
1 parent
a69b3455d3
commit
630c30de79
7 files changed
+429
-80
No files matched your search
@@ -21,7 +21,7 @@ func channelDescriptors(instances []*channelInstance) []status.Descriptor {
|
||||
descriptors = append(descriptors, status.Descriptor{
|
||||
ID: instance.name,
|
||||
Name: instance.name,
|
||||
Configured: true,
|
||||
Configured: instance.current() != nil,
|
||||
// The capability comes from the same place the action does, so a
|
||||
// channel cannot declare reload support and then answer nothing.
|
||||
ReloadSupported: reloadable(instance),
|
||||
@@ -35,7 +35,14 @@ func channelDescriptors(instances []*channelInstance) []status.Descriptor {
|
||||
// a reload performs; deriving them separately is how a dashboard ends up offering
|
||||
// a button that reports success and changes nothing.
|
||||
func reloadable(instance *channelInstance) bool {
|
||||
gateway, ok := instance.current().(*telegram.Gateway)
|
||||
return channelReloadable(instance.current())
|
||||
}
|
||||
|
||||
// channelReloadable reports whether a built channel can re-read its
|
||||
// configuration in place. A disabled channel (nil) cannot, which is what a
|
||||
// channel that enablement turned off should declare.
|
||||
func channelReloadable(ch channels.Channel) bool {
|
||||
gateway, ok := ch.(*telegram.Gateway)
|
||||
return ok && gateway.Reload != nil
|
||||
}
|
||||
|
||||
|
||||
@@ -160,13 +160,15 @@ func compose(ctx context.Context, d deps) (*Service, error) {
|
||||
// still restarted alone rather than through a process restart.
|
||||
func composeChannels(ctx context.Context, d deps) ([]*channelInstance, error) {
|
||||
instances := make([]*channelInstance, 0, 3)
|
||||
if d.Config.TelegramToken != "" {
|
||||
instance, err := composeTelegram(ctx, d)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
instances = append(instances, instance)
|
||||
// Telegram is composed whether or not it is enabled: a channel that
|
||||
// enablement can turn on has to exist for the supervisor to start. Its
|
||||
// channel is nil until a token is configured (composeTelegram). The other
|
||||
// channels are fixed by what the process can build at startup.
|
||||
telegramInstance, err := composeTelegram(ctx, d)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
instances = append(instances, telegramInstance)
|
||||
for _, instance := range d.ExtensionChannels {
|
||||
if slices.ContainsFunc(instances, func(have *channelInstance) bool { return have.name == instance.name }) {
|
||||
d.Log.Warn("channel extension skipped: a built-in channel has the same name", "channel", instance.name)
|
||||
@@ -181,14 +183,14 @@ func composeChannels(ctx context.Context, d deps) ([]*channelInstance, error) {
|
||||
}
|
||||
|
||||
func composeTelegram(ctx context.Context, d deps) (*channelInstance, error) {
|
||||
if len(d.Config.Telegram.AllowedUserIDs) == 0 {
|
||||
d.Log.Warn("chat.telegram has no allowed_user_ids: every sender will be rejected. " +
|
||||
"Add your Telegram user id to chat.telegram.allowed_user_ids to enable the bot.")
|
||||
}
|
||||
build := func(cfg ResolvedConfig) (channels.Channel, error) {
|
||||
if cfg.TelegramToken == "" {
|
||||
return nil, nil
|
||||
}
|
||||
if len(cfg.Telegram.AllowedUserIDs) == 0 {
|
||||
d.Log.Warn("chat.telegram has no allowed_user_ids: every sender will be rejected. " +
|
||||
"Add your Telegram user id to chat.telegram.allowed_user_ids to enable the bot.")
|
||||
}
|
||||
tg := telegram.New(cfg.TelegramToken, cfg.Telegram.AllowedUserIDs, d.Log)
|
||||
tg.Settings = d.Settings
|
||||
configureTelegram(ctx, tg, cfg, d)
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
package archiemessaging
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"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/secret"
|
||||
)
|
||||
|
||||
// startEnablementService composes and starts a service with the Telegram
|
||||
// channel's factory replaced by a scripted channel, so enablement can be driven
|
||||
// without a real bot.
|
||||
func startEnablementService(t *testing.T, ch *fakeChannel) *Service {
|
||||
t.Helper()
|
||||
srv, err := compose(context.Background(), deps{Log: slog.Default()})
|
||||
if err != nil {
|
||||
t.Fatalf("compose: %v", err)
|
||||
}
|
||||
inst := srv.instanceByID("telegram")
|
||||
if inst == nil {
|
||||
t.Fatal("telegram channel was not composed")
|
||||
}
|
||||
inst.rebuild = func(ResolvedConfig) (channels.Channel, error) { return ch, nil }
|
||||
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")
|
||||
}
|
||||
})
|
||||
waitSupervised(t, srv, "telegram")
|
||||
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{}
|
||||
}
|
||||
|
||||
// TestChannelEnablementAppliesLive 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 TestChannelEnablementAppliesLive(t *testing.T) {
|
||||
ch := &fakeChannel{}
|
||||
srv := startEnablementService(t, ch)
|
||||
|
||||
if before := channelByID(t, srv, "telegram"); before.Configured || before.State != status.StateStopped {
|
||||
t.Fatalf("telegram before enable = %+v, want not configured and stopped", before)
|
||||
}
|
||||
|
||||
if err := srv.enableChannel("telegram", ResolvedConfig{TelegramToken: "token"}); err != nil {
|
||||
t.Fatalf("enable: %v", err)
|
||||
}
|
||||
waitStarts(t, ch, 1)
|
||||
if enabled := channelByID(t, srv, "telegram"); !enabled.Configured || enabled.State != status.StateStarting {
|
||||
t.Fatalf("telegram after enable = %+v, want configured and starting", enabled)
|
||||
}
|
||||
|
||||
if err := srv.disableChannel("telegram"); err != nil {
|
||||
t.Fatalf("disable: %v", err)
|
||||
}
|
||||
if disabled := channelByID(t, srv, "telegram"); disabled.Configured || disabled.State != status.StateStopped {
|
||||
t.Fatalf("telegram 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
|
||||
}
|
||||
|
||||
// fakeEngine resolves every key, so a stored token reference is resolvable.
|
||||
type fakeEngine struct{}
|
||||
|
||||
func (fakeEngine) Name() string { return "test" }
|
||||
func (fakeEngine) Resolve(key string) (string, error) { return "token-" + key, nil }
|
||||
|
||||
// TestReconcileOnceEnablesAndDisables drives the whole stored-settings path:
|
||||
// a settings version that configures a token enables the channel and is
|
||||
// recorded as applied only once the channel is running it; a later version
|
||||
// that clears the token disables it.
|
||||
func TestReconcileOnceEnablesAndDisables(t *testing.T) {
|
||||
ch := &fakeChannel{}
|
||||
srv := startEnablementService(t, ch)
|
||||
srv.secrets = secret.NewRegistry()
|
||||
srv.secrets.Register(fakeEngine{})
|
||||
|
||||
srv.settingsSource = fakeSettings{
|
||||
chat: config.ChatConfig{Telegram: config.TelegramConfig{Token: secret.SecretRef{Engine: "test", Key: "bot"}}},
|
||||
version: 1,
|
||||
}
|
||||
if err := srv.reconcileOnce(context.Background()); err != nil {
|
||||
t.Fatalf("reconcile enable: %v", err)
|
||||
}
|
||||
waitStarts(t, ch, 1)
|
||||
if got := channelByID(t, srv, "telegram"); !got.Configured {
|
||||
t.Fatalf("telegram not enabled by reconcile: %+v", got)
|
||||
}
|
||||
if srv.appliedVersion.Load() != 1 {
|
||||
t.Fatalf("appliedVersion = %d after enable, want 1", srv.appliedVersion.Load())
|
||||
}
|
||||
|
||||
srv.settingsSource = fakeSettings{version: 2}
|
||||
if err := srv.reconcileOnce(context.Background()); err != nil {
|
||||
t.Fatalf("reconcile disable: %v", err)
|
||||
}
|
||||
if got := channelByID(t, srv, "telegram"); got.Configured || got.State != status.StateStopped {
|
||||
t.Fatalf("telegram not disabled by reconcile: %+v", got)
|
||||
}
|
||||
if srv.appliedVersion.Load() != 2 {
|
||||
t.Fatalf("appliedVersion = %d after disable, want 2", srv.appliedVersion.Load())
|
||||
}
|
||||
}
|
||||
|
||||
// TestApplyChannelSettingsEnablesAndDisables pins the reconcile entry point:
|
||||
// a settings change that turns a channel on or off starts or stops it and
|
||||
// reports applied, and a tick that changes nothing is a no-op.
|
||||
func TestApplyChannelSettingsEnablesAndDisables(t *testing.T) {
|
||||
ch := &fakeChannel{}
|
||||
srv := startEnablementService(t, ch)
|
||||
|
||||
applied, err := srv.applyChannelSettings(ResolvedConfig{TelegramToken: "token"})
|
||||
if err != nil || !applied {
|
||||
t.Fatalf("enable: applied=%v err=%v", applied, err)
|
||||
}
|
||||
waitStarts(t, ch, 1)
|
||||
if got := channelByID(t, srv, "telegram"); !got.Configured || got.State == status.StateStopped {
|
||||
t.Fatalf("telegram not enabled: %+v", got)
|
||||
}
|
||||
|
||||
applied, err = srv.applyChannelSettings(ResolvedConfig{})
|
||||
if err != nil || !applied {
|
||||
t.Fatalf("disable: applied=%v err=%v", applied, err)
|
||||
}
|
||||
if got := channelByID(t, srv, "telegram"); got.Configured || got.State != status.StateStopped {
|
||||
t.Fatalf("telegram not disabled: %+v", got)
|
||||
}
|
||||
|
||||
applied, err = srv.applyChannelSettings(ResolvedConfig{})
|
||||
if err != nil || !applied {
|
||||
t.Fatalf("no-op tick: applied=%v err=%v", applied, err)
|
||||
}
|
||||
}
|
||||
@@ -85,30 +85,32 @@ func resolveChatSecrets(base ResolvedConfig, layered config.ChatConfig, secrets
|
||||
return next, nil
|
||||
}
|
||||
|
||||
// applyChannelSettings restarts only channels whose transport settings
|
||||
// changed and reports whether every restart succeeded. Enabling or
|
||||
// disabling a channel or changing a listen address needs a process restart.
|
||||
// applyChannelSettings applies the changed channel settings: channels whose
|
||||
// enablement changed are started or stopped, channels whose transport settings
|
||||
// changed are restarted, and the report is success only once every change is in
|
||||
// effect.
|
||||
func (s *Service) applyChannelSettings(next ResolvedConfig) (bool, error) {
|
||||
current := s.currentConfig()
|
||||
effective, outstanding := pinProcessBindings(current, next)
|
||||
|
||||
if next.ShowToolCalls != current.ShowToolCalls {
|
||||
s.applyShowToolCalls(next.ShowToolCalls)
|
||||
}
|
||||
|
||||
applied := true
|
||||
for _, id := range channelChanges(current, effective) {
|
||||
if err := s.restartChannel(id, effective); err != nil {
|
||||
outstanding := s.applyChannelEnablement(current, next)
|
||||
if len(outstanding) > 0 {
|
||||
applied = false
|
||||
}
|
||||
for _, id := range channelChanges(current, next) {
|
||||
if err := s.restartChannel(id, next); err != nil {
|
||||
outstanding = append(outstanding, err.Error())
|
||||
applied = false
|
||||
}
|
||||
}
|
||||
// A failed restart leaves the running configuration in place, so the next
|
||||
// tick sees the same change and retries it. A change that was carried out
|
||||
// (including a binding change that was refused and reported) is recorded, so
|
||||
// it is not applied again on every tick.
|
||||
// A failed change leaves the running configuration in place, so the next
|
||||
// tick sees the same difference and retries it.
|
||||
if applied {
|
||||
s.setConfig(effective)
|
||||
s.setConfig(next)
|
||||
}
|
||||
if len(outstanding) == 0 {
|
||||
return applied, nil
|
||||
@@ -116,6 +118,24 @@ func (s *Service) applyChannelSettings(next ResolvedConfig) (bool, error) {
|
||||
return applied, errors.New(strings.Join(outstanding, "; "))
|
||||
}
|
||||
|
||||
// applyChannelEnablement starts or stops the channels whose enablement the
|
||||
// stored settings changed, and reports only once the requested state is in
|
||||
// effect. A channel whose enablement did not change is left alone.
|
||||
func (s *Service) applyChannelEnablement(current, next ResolvedConfig) []string {
|
||||
var outstanding []string
|
||||
switch {
|
||||
case current.TelegramToken != "" && next.TelegramToken == "":
|
||||
if err := s.disableChannel("telegram"); err != nil {
|
||||
outstanding = append(outstanding, err.Error())
|
||||
}
|
||||
case current.TelegramToken == "" && next.TelegramToken != "":
|
||||
if err := s.enableChannel("telegram", next); err != nil {
|
||||
outstanding = append(outstanding, err.Error())
|
||||
}
|
||||
}
|
||||
return outstanding
|
||||
}
|
||||
|
||||
// applyShowToolCalls updates the running Telegram gateways in place. Nothing
|
||||
// else consumes the setting, and it is read per reply, so it needs no restart.
|
||||
func (s *Service) applyShowToolCalls(show bool) {
|
||||
@@ -126,28 +146,14 @@ func (s *Service) applyShowToolCalls(show bool) {
|
||||
}
|
||||
}
|
||||
|
||||
// pinProcessBindings holds the values a running process cannot change in place:
|
||||
// the set of channels it composed.
|
||||
// The returned configuration keeps the running value for each, and the returned
|
||||
// problems name what the operator changed and when it takes effect.
|
||||
func pinProcessBindings(current, next ResolvedConfig) (ResolvedConfig, []string) {
|
||||
effective := next
|
||||
var problems []string
|
||||
|
||||
if (current.TelegramToken != "") != (next.TelegramToken != "") {
|
||||
problems = append(problems, "chat.telegram enabled/disabled; takes effect on restart")
|
||||
effective.Telegram, effective.TelegramToken = current.Telegram, current.TelegramToken
|
||||
}
|
||||
return effective, problems
|
||||
}
|
||||
|
||||
// channelChanges returns the composed channels whose transport settings differ
|
||||
// between the running and the effective configuration. A channel absent from
|
||||
// current (not composed) never appears, and an unchanged channel is not
|
||||
// restarted.
|
||||
// between the running and the next configuration while remaining enabled. A
|
||||
// channel absent from current (not composed) never appears, an unchanged
|
||||
// channel is not restarted, and an enable or disable is applied as enablement
|
||||
// rather than as a transport change.
|
||||
func channelChanges(current, next ResolvedConfig) []string {
|
||||
var changed []string
|
||||
if current.TelegramToken != "" &&
|
||||
if current.TelegramToken != "" && next.TelegramToken != "" &&
|
||||
(current.TelegramToken != next.TelegramToken || !slices.Equal(current.Telegram.AllowedUserIDs, next.Telegram.AllowedUserIDs)) {
|
||||
changed = append(changed, "telegram")
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/channels"
|
||||
"github.com/samcharles93/archie-core/internal/channels/status"
|
||||
)
|
||||
|
||||
// runChannel supervises one channel for the service's lifetime. It starts the
|
||||
@@ -22,12 +23,23 @@ func (s *Service) runChannel(ctx context.Context, c *channelInstance) {
|
||||
for {
|
||||
c.mu.Lock()
|
||||
ch := c.channel
|
||||
if ch == nil {
|
||||
// Disabled: there is no channel to run until an enable builds one.
|
||||
c.mu.Unlock()
|
||||
s.status.MarkStopped(c.name, "")
|
||||
if s.awaitChannel(ctx, c, 0) == channelShutdown {
|
||||
return
|
||||
}
|
||||
attempts = 0
|
||||
continue
|
||||
}
|
||||
runCtx, cancel := context.WithCancel(ctx)
|
||||
c.cancel = cancel
|
||||
c.mu.Unlock()
|
||||
|
||||
s.log.Info("starting channel", "name", c.name)
|
||||
err := ch.Start(runCtx, s.chat, s.lifecycleFor(c.name))
|
||||
attempts++
|
||||
|
||||
// Decide the next state under the same lock a restart takes, so a
|
||||
// restart racing this exit is either seen here (restartPending) or
|
||||
@@ -47,52 +59,89 @@ func (s *Service) runChannel(ctx context.Context, c *channelInstance) {
|
||||
// idempotent tail for the paths that leave a listener behind.
|
||||
s.stopChannel(ctx, c.name, ch)
|
||||
|
||||
if shutdown {
|
||||
if err != nil && !errors.Is(err, context.Canceled) {
|
||||
s.status.MarkFailed(c.name, err.Error())
|
||||
} else {
|
||||
s.status.MarkStopped(c.name, "")
|
||||
}
|
||||
next, wait := s.afterChannelRun(c, err, shutdown, restart, attempts)
|
||||
if next == nextStop {
|
||||
return
|
||||
}
|
||||
if restart {
|
||||
if next == nextReplaced {
|
||||
attempts = 0
|
||||
continue
|
||||
}
|
||||
if err == nil {
|
||||
// The channel stopped itself. Hold it stopped rather than
|
||||
// spending the failure retry budget on a run that chose to end.
|
||||
s.status.MarkStopped(c.name, "")
|
||||
s.log.Info("channel stopped", "name", c.name)
|
||||
if s.awaitChannel(ctx, c, 0) == channelShutdown {
|
||||
return
|
||||
}
|
||||
attempts = 0
|
||||
continue
|
||||
}
|
||||
attempts++
|
||||
s.status.MarkFailed(c.name, err.Error())
|
||||
if attempts >= s.retry.attempts {
|
||||
s.log.Error("channel failed repeatedly; parked until an explicit restart",
|
||||
"name", c.name, "attempts", attempts, "err", err)
|
||||
if s.awaitChannel(ctx, c, 0) == channelShutdown {
|
||||
return
|
||||
}
|
||||
attempts = 0
|
||||
continue
|
||||
}
|
||||
backoff := s.retry.backoffFor(attempts)
|
||||
s.log.Warn("channel failed; restarting", "name", c.name,
|
||||
"attempt", attempts, "of", s.retry.attempts, "in", backoff, "err", err)
|
||||
switch s.awaitChannel(ctx, c, backoff) {
|
||||
case channelShutdown:
|
||||
if attempts, next = s.holdAfterRun(ctx, c, next, wait, attempts); next == nextStop {
|
||||
return
|
||||
case channelRestart:
|
||||
attempts = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// channelNext is what a supervisor does after one channel run ended.
|
||||
type channelNext int
|
||||
|
||||
const (
|
||||
// nextStop: the service is stopping; the supervisor returns.
|
||||
nextStop channelNext = iota
|
||||
// nextReplaced: a replacement is already in the instance; run it now.
|
||||
nextReplaced
|
||||
// nextPark: hold, with no timer, until an explicit restart or shutdown.
|
||||
nextPark
|
||||
// nextRetry: wait the backoff, then run the same channel again.
|
||||
nextRetry
|
||||
)
|
||||
|
||||
// afterChannelRun records the ended run's state and decides what the supervisor
|
||||
// does next. shutdown is the service stopping; restart is an explicit
|
||||
// replacement already waiting in the instance.
|
||||
func (s *Service) afterChannelRun(c *channelInstance, err error, shutdown, restart bool, attempts int) (channelNext, time.Duration) {
|
||||
switch {
|
||||
case shutdown:
|
||||
if err != nil && !errors.Is(err, context.Canceled) {
|
||||
s.status.MarkFailed(c.name, err.Error())
|
||||
} else {
|
||||
s.status.MarkStopped(c.name, "")
|
||||
}
|
||||
return nextStop, 0
|
||||
case restart:
|
||||
return nextReplaced, 0
|
||||
case err == nil:
|
||||
// The channel stopped itself. Hold it stopped rather than spending the
|
||||
// failure retry budget on a run that chose to end.
|
||||
s.status.MarkStopped(c.name, "")
|
||||
s.log.Info("channel stopped", "name", c.name)
|
||||
return nextPark, 0
|
||||
case attempts >= s.retry.attempts:
|
||||
s.status.MarkFailed(c.name, err.Error())
|
||||
s.log.Error("channel failed repeatedly; parked until an explicit restart",
|
||||
"name", c.name, "attempts", attempts, "err", err)
|
||||
return nextPark, 0
|
||||
default:
|
||||
s.status.MarkFailed(c.name, err.Error())
|
||||
wait := s.retry.backoffFor(attempts)
|
||||
s.log.Warn("channel failed; restarting", "name", c.name,
|
||||
"attempt", attempts, "of", s.retry.attempts, "in", wait, "err", err)
|
||||
return nextRetry, wait
|
||||
}
|
||||
}
|
||||
|
||||
// holdAfterRun waits out a park or a retry backoff, and reports the attempt
|
||||
// count to carry into the next run and whether the supervisor keeps going. A
|
||||
// restart delivered during a backoff starts the replacement with a fresh
|
||||
// budget; a shutdown ends the supervisor.
|
||||
func (s *Service) holdAfterRun(ctx context.Context, c *channelInstance, next channelNext, wait time.Duration, attempts int) (int, channelNext) {
|
||||
if next == nextRetry {
|
||||
switch s.awaitChannel(ctx, c, wait) {
|
||||
case channelShutdown:
|
||||
return attempts, nextStop
|
||||
case channelRestart:
|
||||
return 0, nextReplaced
|
||||
default:
|
||||
return attempts, nextRetry
|
||||
}
|
||||
}
|
||||
if s.awaitChannel(ctx, c, 0) == channelShutdown {
|
||||
return attempts, nextStop
|
||||
}
|
||||
return 0, nextReplaced
|
||||
}
|
||||
|
||||
// channelRetry bounds how a supervisor retries a channel that fails on its own
|
||||
// before parking it for an explicit restart.
|
||||
type channelRetryPolicy struct {
|
||||
@@ -187,10 +236,17 @@ func (s *Service) restartChannel(id string, next ResolvedConfig) error {
|
||||
if replacement == nil {
|
||||
return fmt.Errorf("channel %q has no configuration", id)
|
||||
}
|
||||
return s.setChannelState(c, replacement)
|
||||
}
|
||||
|
||||
// setChannelState swaps the channel a supervisor runs; a nil replacement stops
|
||||
// it. It returns once the supervisor has been told, not once the channel is up:
|
||||
// a caller that needs the observable state awaits it (awaitChannelActive).
|
||||
func (s *Service) setChannelState(c *channelInstance, replacement channels.Channel) error {
|
||||
c.mu.Lock()
|
||||
if !c.supervised {
|
||||
c.mu.Unlock()
|
||||
return fmt.Errorf("channel %q is not running", id)
|
||||
return fmt.Errorf("channel %q is not running", c.name)
|
||||
}
|
||||
c.channel = replacement
|
||||
cancel := c.cancel
|
||||
@@ -215,6 +271,75 @@ func (s *Service) restartChannel(id string, next ResolvedConfig) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// enableChannel builds and starts a channel that a settings change turned on,
|
||||
// and reports only once it is no longer stopped.
|
||||
func (s *Service) enableChannel(id string, next ResolvedConfig) error {
|
||||
c := s.instanceByID(id)
|
||||
if c == nil {
|
||||
return fmt.Errorf("no channel %q", id)
|
||||
}
|
||||
if c.rebuild == nil {
|
||||
return fmt.Errorf("channel %q cannot be rebuilt", id)
|
||||
}
|
||||
replacement, err := c.rebuild(next)
|
||||
if err != nil {
|
||||
return fmt.Errorf("build %q: %w", id, err)
|
||||
}
|
||||
if replacement == nil {
|
||||
return fmt.Errorf("channel %q has no configuration", id)
|
||||
}
|
||||
if err := s.setChannelState(c, replacement); err != nil {
|
||||
return err
|
||||
}
|
||||
s.status.Declare(id, true, channelReloadable(replacement))
|
||||
s.signalPublish()
|
||||
return s.awaitChannelActive(id, true)
|
||||
}
|
||||
|
||||
// disableChannel stops a channel that a settings change turned off, and reports
|
||||
// only once it has stopped.
|
||||
func (s *Service) disableChannel(id string) error {
|
||||
c := s.instanceByID(id)
|
||||
if c == nil || c.current() == nil {
|
||||
return nil
|
||||
}
|
||||
if err := s.setChannelState(c, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
s.status.Declare(id, false, false)
|
||||
s.signalPublish()
|
||||
return s.awaitChannelActive(id, false)
|
||||
}
|
||||
|
||||
// channelApplyTimeout bounds how long reconcile waits for an enable or disable
|
||||
// to take effect before reporting it unapplied, which leaves the next tick to
|
||||
// retry it.
|
||||
const channelApplyTimeout = 5 * time.Second
|
||||
|
||||
// channelApplyPoll is how often that wait re-reads the channel's state.
|
||||
const channelApplyPoll = 10 * time.Millisecond
|
||||
|
||||
// awaitChannelActive waits, up to channelApplyTimeout, for a channel to leave
|
||||
// or reach the stopped state, so an enable or disable is reported applied only
|
||||
// once the channel is actually running (or not) rather than merely queued.
|
||||
func (s *Service) awaitChannelActive(id string, active bool) error {
|
||||
deadline := time.Now().Add(channelApplyTimeout)
|
||||
for {
|
||||
for _, st := range s.status.Snapshot() {
|
||||
if st.ID == id && (st.State != status.StateStopped) == active {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
if active {
|
||||
return fmt.Errorf("channel %q did not start", id)
|
||||
}
|
||||
return fmt.Errorf("channel %q did not stop", id)
|
||||
}
|
||||
time.Sleep(channelApplyPoll)
|
||||
}
|
||||
}
|
||||
|
||||
// stopChannel closes one channel's listener with its own bounded context, so a
|
||||
// stop that hangs cannot hold the shutdown past the configured timeout. The
|
||||
// parent context is stripped of its cancellation because this runs on the
|
||||
|
||||
@@ -23,10 +23,13 @@ type fakeChannel struct {
|
||||
|
||||
func (f *fakeChannel) Name() string { return "fake" }
|
||||
|
||||
func (f *fakeChannel) Start(ctx context.Context, _ messaging.ChatContract, _ channels.Lifecycle) error {
|
||||
func (f *fakeChannel) Start(ctx context.Context, _ messaging.ChatContract, lifecycle channels.Lifecycle) error {
|
||||
f.mu.Lock()
|
||||
f.starts++
|
||||
f.mu.Unlock()
|
||||
if lifecycle.Starting != nil {
|
||||
lifecycle.Starting()
|
||||
}
|
||||
if f.runErr != nil {
|
||||
return f.runErr
|
||||
}
|
||||
|
||||
@@ -74,6 +74,24 @@ func (m *Manager) MarkDegraded(id, detail string) {
|
||||
func (m *Manager) MarkFailed(id, detail string) { m.set(id, StateFailed, detail) }
|
||||
func (m *Manager) MarkStopped(id, detail string) { m.set(id, StateStopped, detail) }
|
||||
|
||||
// Declare records whether a composed channel is currently configured and
|
||||
// reloadable. A live enable or disable changes both without changing the
|
||||
// channel's identity, so the operator-facing declaration follows the channel
|
||||
// rather than being fixed at composition.
|
||||
func (m *Manager) Declare(id string, configured, reloadSupported bool) {
|
||||
if m == nil {
|
||||
return
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
i, ok := m.index[id]
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
m.channels[i].Configured = configured
|
||||
m.channels[i].ReloadSupported = reloadSupported
|
||||
}
|
||||
|
||||
func (m *Manager) set(id string, state State, detail string) {
|
||||
if m == nil {
|
||||
return
|
||||
|
||||
Reference in new issue
Block a user