fix(channels): call MarkRunning once a channel is actually up

channels.Manager.MarkRunning was never called for telegram, email, or
webhook -- every start path only called MarkStarting then MarkFailed
on error, so the dashboard showed a working channel stuck on
"Starting" forever (confirmed live: Telegram polling and delivering
messages while /api/channels still reported "starting").

Adds gateway.Lifecycle{Starting, Running func()}, threaded through
Gateway.Start(ctx, router, lifecycle). Email and webhook report
Running once their listener actually binds -- webhook moves off
http.Server.ListenAndServe's internal bind to an explicit
net.ListenConfig.Listen so binding is observable before Serve.
Telegram reports Running after StartWebhook launches in webhook mode,
or after the first successful getUpdates response in long-poll mode,
observed via a pollReadinessClient http.Client wrapper since the
go-telegram/bot library keeps polling errors inside its own worker
goroutine. Restart re-reports Starting/Running each cycle.
This commit is contained in:
sam committed 2026-09-02 20:47:01 +10:00
1 parent f4111e7208
commit f820a89e32
13 files changed
+369 -30

No files matched your search

+16 -6
View File
@@ -557,14 +557,19 @@ func (b *boot) setupGateways(ctx context.Context, cfgPath, overlayPath string) b
emRouter := gateway.NewRouter(b.st, nil, "email")
configureTaskCommands(emRouter, b.chatTasks, b.chatController, b.defaultChatIdentity)
b.startGateways = append(b.startGateways, func() {
b.channelManager.MarkStarting("email")
go func() {
if err := em.Start(ctx, emRouter); err != nil && ctx.Err() == nil {
lifecycle := gateway.Lifecycle{
Starting: func() { b.channelManager.MarkStarting("email") },
Running: func() {
b.channelManager.MarkRunning("email")
log.Info("email gateway started", "addr", cfg.Chat.Email.ListenAddr)
},
}
if err := em.Start(ctx, emRouter, lifecycle); err != nil && ctx.Err() == nil {
b.channelManager.MarkFailed("email", err.Error())
log.Error("email gateway stopped", "err", err)
}
}()
log.Info("email gateway started", "addr", cfg.Chat.Email.ListenAddr)
})
}
@@ -580,14 +585,19 @@ func (b *boot) setupGateways(ctx context.Context, cfgPath, overlayPath string) b
whRouter := gateway.NewRouter(b.st, nil, "webhook")
configureTaskCommands(whRouter, b.chatTasks, b.chatController, b.defaultChatIdentity)
b.startGateways = append(b.startGateways, func() {
b.channelManager.MarkStarting("webhook")
go func() {
if err := wh.Start(ctx, whRouter); err != nil && ctx.Err() == nil {
lifecycle := gateway.Lifecycle{
Starting: func() { b.channelManager.MarkStarting("webhook") },
Running: func() {
b.channelManager.MarkRunning("webhook")
log.Info("webhook gateway started", "addr", fmt.Sprintf("%s:%d", host, port))
},
}
if err := wh.Start(ctx, whRouter, lifecycle); err != nil && ctx.Err() == nil {
b.channelManager.MarkFailed("webhook", err.Error())
log.Error("webhook gateway stopped", "err", err)
}
}()
log.Info("webhook gateway started", "addr", fmt.Sprintf("%s:%d", host, port))
})
}
return true
@@ -0,0 +1,77 @@
package archied
import (
"context"
"log/slog"
"path/filepath"
"testing"
"time"
channelruntime "github.com/samcharles93/archie-core/internal/channels"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/store"
"github.com/samcharles93/archie-core/internal/webui"
)
func TestConfiguredNetworkGatewaysBecomeRunning(t *testing.T) {
tests := []struct {
name string
id string
cfg config.Config
}{
{
name: "email",
id: "email",
cfg: config.Config{Chat: config.ChatConfig{Email: config.EmailConfig{
ListenAddr: "127.0.0.1:0",
}}},
},
{
name: "webhook",
id: "webhook",
cfg: config.Config{Chat: config.ChatConfig{
WebhookAddr: "127.0.0.1:0",
}},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
st, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "archie.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = st.Close() })
manager := channelruntime.NewManager([]channelruntime.Descriptor{{
ID: test.id, Name: test.name, Configured: true,
}})
b := &boot{
cfg: test.cfg,
log: slog.New(slog.DiscardHandler),
st: st,
channelManager: manager,
web: &webui.Server{},
}
ctx, cancel := context.WithCancel(t.Context())
t.Cleanup(cancel)
if ok := b.setupGateways(ctx, "", ""); !ok {
t.Fatal("setupGateways returned false")
}
if len(b.startGateways) != 1 {
t.Fatalf("start gateways = %d, want 1", len(b.startGateways))
}
b.startGateways[0]()
deadline := time.Now().Add(250 * time.Millisecond)
for time.Now().Before(deadline) {
if got := manager.Snapshot()[0].State; got == channelruntime.StateRunning {
return
}
time.Sleep(time.Millisecond)
}
t.Fatalf("channel state = %q, want %q after successful startup",
manager.Snapshot()[0].State, channelruntime.StateRunning)
})
}
}
+14 -5
View File
@@ -114,18 +114,27 @@ func setupTelegramGateway(ctx context.Context, s telegramSetup) (start func(), o
}
router := buildTelegramRouter(ctx, tg, s, sessionStore)
return func() {
if s.ChannelManager != nil {
s.ChannelManager.MarkStarting("telegram")
}
go func() {
if err := tg.Start(ctx, router); err != nil && ctx.Err() == nil {
lifecycle := gateway.Lifecycle{
Starting: func() {
if s.ChannelManager != nil {
s.ChannelManager.MarkStarting("telegram")
}
},
Running: func() {
if s.ChannelManager != nil {
s.ChannelManager.MarkRunning("telegram")
}
s.Log.Info("telegram gateway started")
},
}
if err := tg.Start(ctx, router, lifecycle); err != nil && ctx.Err() == nil {
if s.ChannelManager != nil {
s.ChannelManager.MarkFailed("telegram", err.Error())
}
s.Log.Error("telegram gateway stopped", "err", err)
}
}()
s.Log.Info("telegram gateway started")
}, true
}
+3 -1
View File
@@ -57,7 +57,8 @@ func (g *Gateway) Name() string { return "email" }
// Start begins listening for SMTP connections. Blocks until ctx is
// cancelled.
func (g *Gateway) Start(ctx context.Context, router *gateway.Router) error {
func (g *Gateway) Start(ctx context.Context, router *gateway.Router, lifecycle gateway.Lifecycle) error {
lifecycle.ReportStarting()
g.mu.Lock()
g.router = router
g.mu.Unlock()
@@ -72,6 +73,7 @@ func (g *Gateway) Start(ctx context.Context, router *gateway.Router) error {
g.mu.Unlock()
g.log.Info("email gateway listening", "addr", g.ListenAddr)
lifecycle.ReportRunning()
go func() {
<-ctx.Done()
+1 -1
View File
@@ -85,7 +85,7 @@ func TestSMTPReceiveAndRoute(t *testing.T) {
_ = ln.Close()
g.ListenAddr = addr
go func() { _ = g.Start(ctx, router) }()
go func() { _ = g.Start(ctx, router, gateway.Lifecycle{}) }()
time.Sleep(20 * time.Millisecond)
defer func() { _ = g.Stop(context.Background()) }()
@@ -0,0 +1,68 @@
package telegram
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"sync/atomic"
"time"
"github.com/go-telegram/bot"
"github.com/go-telegram/bot/models"
)
const telegramPollTimeout = time.Minute
// pollReadinessClient observes the same successful getUpdates response the
// Telegram library is about to decode. The library keeps polling errors inside
// its worker goroutine, so the HTTP boundary is the only place Start can prove
// that long polling is actually usable instead of merely spawned.
type pollReadinessClient struct {
client bot.HttpClient
onRunning func()
reported atomic.Bool
}
func (c *pollReadinessClient) Do(req *http.Request) (*http.Response, error) {
resp, err := c.client.Do(req)
if err != nil || c.reported.Load() || !strings.HasSuffix(req.URL.Path, "/getUpdates") {
return resp, err
}
body, err := io.ReadAll(resp.Body)
closeErr := resp.Body.Close()
if err != nil {
return nil, fmt.Errorf("read Telegram polling response: %w", err)
}
resp.Body = &replayBody{Reader: bytes.NewReader(body), closeErr: closeErr}
if successfulPollResponse(body) && c.reported.CompareAndSwap(false, true) && c.onRunning != nil {
c.onRunning()
}
return resp, nil
}
func successfulPollResponse(body []byte) bool {
var response struct {
OK bool `json:"ok"`
Result json.RawMessage `json:"result"`
}
if err := json.Unmarshal(body, &response); err != nil || !response.OK {
return false
}
var updates []*models.Update
return json.Unmarshal(response.Result, &updates) == nil
}
type replayBody struct {
*bytes.Reader
closeErr error
}
func (b *replayBody) Close() error {
err := b.closeErr
b.closeErr = nil
return err
}
@@ -0,0 +1,26 @@
package telegram
import "testing"
func TestSuccessfulPollResponse(t *testing.T) {
tests := []struct {
name string
body string
want bool
}{
{name: "successful empty poll", body: `{"ok":true,"result":[]}`, want: true},
{name: "successful poll with update", body: `{"ok":true,"result":[{"update_id":1}]}`, want: true},
{name: "Telegram API error", body: `{"ok":false,"error_code":409}`, want: false},
{name: "malformed JSON", body: `{`, want: false},
{name: "malformed result", body: `{"ok":true,"result":{}}`, want: false},
{name: "missing result", body: `{"ok":true}`, want: false},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if got := successfulPollResponse([]byte(test.body)); got != test.want {
t.Fatalf("successfulPollResponse() = %v, want %v", got, test.want)
}
})
}
}
+14 -5
View File
@@ -207,15 +207,16 @@ func (g *Gateway) RequestRestart() error {
// Restarts are scoped to this gateway. The daemon keeps running, so
// in-flight agent tasks are untouched -- the whole point of the escape
// hatch is to recover chat without disturbing work in progress.
func (g *Gateway) Start(ctx context.Context, router *gateway.Router) error {
func (g *Gateway) Start(ctx context.Context, router *gateway.Router, lifecycle gateway.Lifecycle) error {
if g.Token == "" {
return fmt.Errorf("telegram bot token is required")
}
g.log.Info("starting telegram gateway")
for {
lifecycle.ReportStarting()
runCtx, cancel := context.WithCancel(ctx)
b, err := g.launch(runCtx, router)
b, err := g.launch(runCtx, router, lifecycle)
if err != nil {
cancel()
return err
@@ -250,9 +251,10 @@ func (g *Gateway) Start(ctx context.Context, router *gateway.Router) error {
}
}
// launch builds one bot instance, registers handlers and begins receiving.
// It returns as soon as delivery is running; the caller owns ctx.
func (g *Gateway) launch(ctx context.Context, router *gateway.Router) (*bot.Bot, error) {
// launch builds one bot instance, registers handlers and starts its delivery
// worker. Webhook readiness is synchronous; long-poll readiness is reported by
// pollReadinessClient after the first successful getUpdates response.
func (g *Gateway) launch(ctx context.Context, router *gateway.Router, lifecycle gateway.Lifecycle) (*bot.Bot, error) {
// Turns are per-launch. Each queued turn carries the update handler's
// context, which is this launch's, so a /restart cancels everything
// still running under the outgoing bot instance.
@@ -270,6 +272,12 @@ func (g *Gateway) launch(ctx context.Context, router *gateway.Router) (*bot.Bot,
if g.WebhookSecret != "" {
opts = append(opts, bot.WithWebhookSecretToken(g.WebhookSecret))
}
if g.WebhookURL == "" {
opts = append(opts, bot.WithHTTPClient(telegramPollTimeout, &pollReadinessClient{
client: &http.Client{Timeout: telegramPollTimeout},
onRunning: lifecycle.ReportRunning,
}))
}
if g.serverURL != "" {
opts = append(opts, bot.WithServerURL(g.serverURL), bot.WithSkipGetMe())
}
@@ -334,6 +342,7 @@ func (g *Gateway) launch(ctx context.Context, router *gateway.Router) (*bot.Bot,
g.webhookCancel = cancel
g.running = true
go b.StartWebhook(webhookCtx)
lifecycle.ReportRunning()
} else {
g.dropPendingUpdates(ctx, b)
g.running = true
+112 -3
View File
@@ -234,9 +234,118 @@ func TestStartWithoutToken(t *testing.T) {
router := gateway.NewRouter(nil, nil, "telegram")
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
if err := g.Start(ctx, router); err == nil {
called := false
if err := g.Start(ctx, router, gateway.Lifecycle{Running: func() { called = true }}); err == nil {
t.Error("expected error when starting without token")
}
if called {
t.Error("running callback fired after failed startup")
}
}
func TestStartReportsRunningAfterLaunch(t *testing.T) {
pollStarted := make(chan struct{})
releasePoll := make(chan struct{})
var firstPoll sync.Once
api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if strings.HasSuffix(r.URL.Path, "getUpdates") {
firstPoll.Do(func() { close(pollStarted) })
select {
case <-releasePoll:
case <-r.Context().Done():
return
}
_, _ = w.Write([]byte(`{"ok":true,"result":[]}`))
return
}
_, _ = w.Write([]byte(`{"ok":true,"result":true}`))
}))
defer api.Close()
g := New("1:test", "", "", []int64{42}, slog.New(slog.DiscardHandler))
g.serverURL = api.URL
ctx, cancel := context.WithCancel(t.Context())
started := make(chan bool, 1)
errCh := make(chan error, 1)
go func() {
errCh <- g.Start(ctx, gateway.NewRouter(nil, nil, "telegram"), gateway.Lifecycle{
Running: func() { started <- g.running },
})
}()
select {
case <-pollStarted:
case <-time.After(time.Second):
t.Fatal("Telegram long poll did not start")
}
select {
case <-started:
t.Fatal("running callback fired before the first successful long poll")
default:
}
close(releasePoll)
select {
case running := <-started:
if !running {
t.Fatal("running callback fired before Telegram delivery started")
}
case <-time.After(time.Second):
t.Fatal("running callback was not fired after Telegram launched")
}
cancel()
if err := <-errCh; err != nil {
t.Fatalf("Start returned an error after cancellation: %v", err)
}
}
func TestStartReportsStartingOnRestart(t *testing.T) {
api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if strings.HasSuffix(r.URL.Path, "getUpdates") {
_, _ = w.Write([]byte(`{"ok":true,"result":[]}`))
return
}
_, _ = w.Write([]byte(`{"ok":true,"result":true}`))
}))
defer api.Close()
g := New("1:test", "", "", []int64{42}, slog.New(slog.DiscardHandler))
g.serverURL = api.URL
ctx, cancel := context.WithCancel(t.Context())
events := make(chan string, 4)
errCh := make(chan error, 1)
go func() {
errCh <- g.Start(ctx, gateway.NewRouter(nil, nil, "telegram"), gateway.Lifecycle{
Starting: func() { events <- "starting" },
Running: func() { events <- "running" },
})
}()
wantEvent(t, events, "starting")
wantEvent(t, events, "running")
if err := g.RequestRestart(); err != nil {
t.Fatal(err)
}
wantEvent(t, events, "starting")
wantEvent(t, events, "running")
cancel()
if err := <-errCh; err != nil {
t.Fatalf("Start returned an error after cancellation: %v", err)
}
}
func wantEvent(t *testing.T, events <-chan string, want string) {
t.Helper()
select {
case got := <-events:
if got != want {
t.Fatalf("lifecycle event = %q, want %q", got, want)
}
case <-time.After(time.Second):
t.Fatalf("timed out waiting for lifecycle event %q", want)
}
}
func TestWebhookHandlerReturns503WhenNotStarted(t *testing.T) {
@@ -275,7 +384,7 @@ func TestStartAndStopLifecycle(t *testing.T) {
// and our test server doesn't return a valid User object.
// The point: we exercise the Start/Stop path; accept either
// success or failure.
_ = g.Start(ctx, router)
_ = g.Start(ctx, router, gateway.Lifecycle{})
// Best-effort stop -- don't assert on Start result since we can't
// fully mock the Bot API without the library supporting a base URL
// override.
@@ -521,7 +630,7 @@ func TestLaunchDropsPendingUpdatesBeforePolling(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
if _, err := g.launch(ctx, nil); err != nil {
if _, err := g.launch(ctx, nil, gateway.Lifecycle{}); err != nil {
t.Fatalf("launch() error = %v", err)
}
cancel()
+14 -4
View File
@@ -6,9 +6,11 @@ package webhook
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"strings"
"sync"
@@ -65,7 +67,8 @@ func (g *Gateway) Name() string { return "webhook" }
// Start begins listening on the configured host:port. Blocks until ctx
// is cancelled.
func (g *Gateway) Start(ctx context.Context, router *gateway.Router) error {
func (g *Gateway) Start(ctx context.Context, router *gateway.Router, lifecycle gateway.Lifecycle) error {
lifecycle.ReportStarting()
g.mu.Lock()
g.router = router
@@ -77,18 +80,25 @@ func (g *Gateway) Start(ctx context.Context, router *gateway.Router) error {
addr := fmt.Sprintf("%s:%d", g.Host, g.Port)
g.server = &http.Server{Addr: addr, Handler: mux}
server := g.server
g.mu.Unlock()
lc := net.ListenConfig{}
ln, err := lc.Listen(ctx, "tcp", addr)
if err != nil {
return fmt.Errorf("webhook: listen: %w", err)
}
g.log.Info("webhook gateway listening", "addr", addr)
lifecycle.ReportRunning()
go func() {
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
defer cancel()
_ = g.server.Shutdown(shutdownCtx)
_ = server.Shutdown(shutdownCtx)
}()
err := g.server.ListenAndServe()
if err != nil && err != http.ErrServerClosed {
err = server.Serve(ln)
if err != nil && !errors.Is(err, http.ErrServerClosed) {
return fmt.Errorf("webhook: listen: %w", err)
}
return nil
+1 -1
View File
@@ -132,7 +132,7 @@ func TestWebhookStartStop(t *testing.T) {
defer cancel()
router := gateway.NewRouter(nil, nil, "webhook")
go func() { _ = g.Start(ctx, router) }()
go func() { _ = g.Start(ctx, router, gateway.Lifecycle{}) }()
time.Sleep(30 * time.Millisecond)
_ = g.Stop(context.Background())
+22 -3
View File
@@ -69,12 +69,31 @@ type Message struct {
At time.Time
}
// Lifecycle receives adapter-owned startup facts. Callbacks are optional.
// Starting is reported before each launch attempt; Running is reported only
// after the adapter's external delivery boundary is ready.
type Lifecycle struct {
Starting func()
Running func()
}
func (l Lifecycle) ReportStarting() {
if l.Starting != nil {
l.Starting()
}
}
func (l Lifecycle) ReportRunning() {
if l.Running != nil {
l.Running()
}
}
// A Gateway owns a persistent connection to a chat channel. Start blocks;
// the gateway should remain running until ctx is cancelled or Stop is
// called.
// the gateway should remain running until ctx is cancelled or Stop is called.
type Gateway interface {
Name() string
Start(ctx context.Context, router *Router) error
Start(ctx context.Context, router *Router, lifecycle Lifecycle) error
Stop(ctx context.Context) error
}