Files
archie/internal/channels/telegram/polling_readiness.go
T
sam c7e3bf190e 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.
2026-09-02 20:47:01 +10:00

69 lines
1.7 KiB
Go

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
}