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:
1 parent
f4111e7208
commit
f820a89e32
13 files changed
+369
-30
No files matched your search
+1
-1
@@ -184,7 +184,7 @@
|
||||
{"_type":"issue","id":"archie-core-1786637501129-428-accd2926","title":"gate output: stop discarding it, put the real error in the park reason","description":"Part of #450.\n\n`StageBaselineGate` in `internal/domain/workflow/implement.go` runs each\n`[[repos.gate]]` command via `cmd.CombinedOutput()`, clips the output to\n200 characters into a `tc.Log.Warn` call, and discards the rest. The\neventual park error (`baseline red -- %s fails and builder could not\nauto-fix (status: %s)`) is built from `res.Status` alone.\n\nWrite the full `CombinedOutput()` to the task's log sink (see #451 for the\nsink itself; this can land first using a plain file write if the sink isn't\nready yet, then be migrated) and put a bounded tail (~2KB, not 200 bytes) of\nit into the returned error so it reaches the park reason.\n\nRed-then-green: write a test against `StageBaselineGate` that asserts the\nreturned error contains gate output beyond 200 characters when the gate\ncommand fails with a long message, confirm it fails today, then fix.","status":"closed","priority":2,"issue_type":"task","created_at":"2026-08-09T06:06:22Z","updated_at":"2026-08-09T08:17:27Z","closed_at":"2026-08-09T08:17:28Z","external_ref":"https://github.com/samcharles93/archie-core/issues/451","source_system":"github:https://github.com/samcharles93/archie-core/issues/451:451","metadata":null,"labels":["task"],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-1786637501090-427-c465db57","title":"epic: task observability — capture and surface agent/gate output","description":"Design doc: `docs/architecture/observability.md` (this branch/PR).\n\n## Problem\n\nA task's real work happens in an ephemeral `archie-agent` container over\nNATS. Four things currently destroy the evidence of what it did:\n\n1. `cmd/archie-agent/main.go` logs to stderr only, and\n `internal/container/pool.go` creates containers with `AutoRemove: true` —\n the log dies with the container.\n2. `StageBaselineGate` (`internal/domain/workflow/implement.go`) captures\n full gate output via `CombinedOutput()`, clips it to 200 chars into a\n `Warn` log, and discards the rest — the park reason carries only a status\n string.\n3. `agentexec.Result` has no step-level transcript (tool calls, durations,\n errors).\n4. `agentexec.SubjectForSystem` is documented as the return channel for\n exactly this (\"log dumps, health... the daemon reads these for\n observability\") but has zero publishers and zero consumers anywhere in\n the codebase.\n\nConsequence: a task parked today with\n`stage baseline: baseline red -- go build ./... fails and builder could not\nauto-fix (status: parked)` and there was no way, from the dashboard or from\nchat, to see the actual `go build` error — the container that had it was\nalready gone.\n\nThis matters beyond convenience: archied is meant to run unattended for\nweeks (`CLAUDE.md` deployment model) and potentially for users other than\nits original operator. A system only debuggable by someone watching\n`docker ps` live doesn't meet that bar.\n\n## Decision\n\nNATS is the only transport this targets. `[agent] mode = \"nats\"` is the\nsupported deployment and the agent must already reach NATS to report any\nstage result — a container that can't reach NATS is a distinct, narrower\nfailure (connectivity) than this epic addresses (a connected container's own\noutput being unrecoverable). No new functionality goes into the in-process\nrunner, which is being migrated away.\n\n## Subtasks\n\nSee linked sub-issues.","status":"closed","priority":2,"issue_type":"epic","created_at":"2026-08-09T06:05:57Z","updated_at":"2026-08-09T09:29:41Z","closed_at":"2026-08-09T09:29:42Z","external_ref":"https://github.com/samcharles93/archie-core/issues/450","source_system":"github:https://github.com/samcharles93/archie-core/issues/450:450","metadata":null,"labels":["epic"],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-1786637501063-426-9fce1209","title":"webui(chat): Send button passes the click event as sendMessage's retry arg, throws and no-ops","description":"`ui/src/chat/chat.js` line 283:\n\n```js\nsend.onclick = sendMessage;\n```\n\n`sendMessage(retry = null)` is assigned directly as a DOM `onclick` handler. The browser invokes `onclick` handlers with the triggering `MouseEvent` as the first argument, so every click calls `sendMessage(event)` -- the click event becomes `retry`. It's truthy and has no `.turn` property, so the very first line of the function:\n\n```js\nconst text = retry?.turn.text || composer.value.trim();\n```\n\nthrows `TypeError: can't access property \"text\", t.turn is undefined` (`t` being the minified param name) immediately, before any state changes (the disable/status-update code runs after this line). The click is silently swallowed -- no message sent, no visible error, Send just does nothing.\n\nReported live on carina 2026-08-09: clicking Send in the dashboard chat had no effect; browser console showed the above uncaught promise rejection at `index.js:77`.\n\n### Fix\n\n`send.onclick = () =\u003e sendMessage();` (matching the pattern already used for `newChat.onclick` a few lines up), so no arguments reach `sendMessage` from the click event.\n","status":"closed","priority":2,"issue_type":"bug","created_at":"2026-08-08T16:31:50Z","updated_at":"2026-08-08T16:34:57Z","closed_at":"2026-08-08T16:34:58Z","external_ref":"https://github.com/samcharles93/archie-core/issues/447","source_system":"github:https://github.com/samcharles93/archie-core/issues/447:447","metadata":null,"labels":["bug"],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-1786637501039-425-88078ff7","title":"channels: MarkRunning is never called, dashboard shows working channels stuck on 'Starting'","description":"`internal/channels.Manager` has `MarkRunning(id)` (`internal/channels/manager.go:68`), but nothing in `cmd/archied/main.go` or `cmd/archied/telegram_setup.go` ever calls it. Every channel start path only calls `MarkStarting` then, on failure, `MarkFailed` -- there's no success signal.\n\n`cmd/archied/telegram_setup.go` around line 100-111:\n\n```go\nif s.ChannelManager != nil {\n s.ChannelManager.MarkStarting(\"telegram\")\n}\ngo func() {\n if err := tg.Start(ctx, router); err != nil \u0026\u0026 ctx.Err() == nil {\n if s.ChannelManager != nil {\n s.ChannelManager.MarkFailed(\"telegram\", err.Error())\n }\n s.Log.Error(\"telegram gateway stopped\", \"err\", err)\n }\n}()\ns.Log.Info(\"telegram gateway started\")\n```\n\n`tg.Start()` blocks for as long as the gateway is healthy (long-poll loop), so there's no point where success can be observed by return value the way failure is. Same pattern for email/webhook in `cmd/archied/main.go` (`channelManager.MarkStarting(\"email\"/\"webhook\")` / `MarkFailed` only).\n\n### Impact\n\nThe Channels dashboard page shows a configured, actually-working channel stuck on \"Starting.\" forever -- confirmed live on carina: Telegram successfully polling, command menu registered, messages flowing, but `/api/channels` still reports `\"state\": \"starting\"` indefinitely.\n\n### Expected\n\nEach channel's start path needs a `MarkRunning(id)` call once it's actually confirmed up -- e.g. after the first successful long-poll/webhook-registration/listener-bind, not just at goroutine launch. Applies to telegram, email, and webhook.\n","status":"in_progress","priority":2,"issue_type":"bug","assignee":"Sam Catlow","created_at":"2026-08-08T16:27:19Z","updated_at":"2026-09-02T10:18:01Z","started_at":"2026-09-02T10:18:01Z","lease_expires_at":"2026-09-02T10:23:01Z","heartbeat_at":"2026-09-02T10:18:01Z","external_ref":"https://github.com/samcharles93/archie-core/issues/446","source_system":"github:https://github.com/samcharles93/archie-core/issues/446:446","metadata":null,"labels":["bug"],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-1786637501039-425-88078ff7","title":"channels: MarkRunning is never called, dashboard shows working channels stuck on 'Starting'","description":"`internal/channels.Manager` has `MarkRunning(id)` (`internal/channels/manager.go:68`), but nothing in `cmd/archied/main.go` or `cmd/archied/telegram_setup.go` ever calls it. Every channel start path only calls `MarkStarting` then, on failure, `MarkFailed` -- there's no success signal.\n\n`cmd/archied/telegram_setup.go` around line 100-111:\n\n```go\nif s.ChannelManager != nil {\n s.ChannelManager.MarkStarting(\"telegram\")\n}\ngo func() {\n if err := tg.Start(ctx, router); err != nil \u0026\u0026 ctx.Err() == nil {\n if s.ChannelManager != nil {\n s.ChannelManager.MarkFailed(\"telegram\", err.Error())\n }\n s.Log.Error(\"telegram gateway stopped\", \"err\", err)\n }\n}()\ns.Log.Info(\"telegram gateway started\")\n```\n\n`tg.Start()` blocks for as long as the gateway is healthy (long-poll loop), so there's no point where success can be observed by return value the way failure is. Same pattern for email/webhook in `cmd/archied/main.go` (`channelManager.MarkStarting(\"email\"/\"webhook\")` / `MarkFailed` only).\n\n### Impact\n\nThe Channels dashboard page shows a configured, actually-working channel stuck on \"Starting.\" forever -- confirmed live on carina: Telegram successfully polling, command menu registered, messages flowing, but `/api/channels` still reports `\"state\": \"starting\"` indefinitely.\n\n### Expected\n\nEach channel's start path needs a `MarkRunning(id)` call once it's actually confirmed up -- e.g. after the first successful long-poll/webhook-registration/listener-bind, not just at goroutine launch. Applies to telegram, email, and webhook.\n","status":"closed","priority":2,"issue_type":"bug","assignee":"Sam Catlow","created_at":"2026-08-08T16:27:19Z","updated_at":"2026-09-02T10:47:01Z","started_at":"2026-09-02T10:18:01Z","closed_at":"2026-09-02T10:47:01Z","close_reason":"MarkRunning now fires for telegram/email/webhook via a gateway.Lifecycle{Starting,Running} callback threaded through Gateway.Start: email/webhook report Running after their listener actually binds (webhook moved off ListenAndServe's internal bind to explicit net.Listen so this is observable), telegram reports Running after StartWebhook launch (webhook mode) or after the first successful getUpdates response via a pollReadinessClient http.Client wrapper (long-poll mode). Restart re-reports Starting/Running each cycle. task check clean, race-clean on the new tests.","external_ref":"https://github.com/samcharles93/archie-core/issues/446","source_system":"github:https://github.com/samcharles93/archie-core/issues/446:446","metadata":null,"labels":["bug"],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-1786637501009-424-5b8332dd","title":"daemon: label dispatch trigger with empty label matches every open issue","description":"`internal/daemon/daemon.go` `pollIssuesWithConfig()`, the `\"label\"` (and `\"either\"`) trigger branch calls:\n\n```go\nissues, err := fg.IssuesWithLabel(ctx, repo.Owner, repo.Name, cfg.Label)\n```\n\n`cfg.Label` is a top-level `Config.Label` field (`internal/config/config.go:364`) -- a different field from `[dispatch.labels]`, which maps task *states* (queued/working/waiting/pr/parked) to their forge labels for a different purpose. It's easy to configure `[dispatch.labels]` and reasonably assume the label-trigger match target is covered, while leaving the actual `label` field that controls trigger matching unset.\n\n`GitHubClient.IssuesWithLabel` (`internal/forge/github.go:103`) passes that straight through as `Labels: []string{label}` to the GitHub issues-list API. With `label == \"\"`, GitHub does not filter by label at all -- it returns every open issue in the repo.\n\n### Impact (live incident, 2026-08-09)\n\nDeployed `dispatch.trigger = \"label\"` on carina without setting `label`. The daemon queued 124 unrelated open issues in one poll cycle (everything from epics to unrelated feature requests), and one reached a running agent container before it was caught and stopped manually.\n\n### Expected\n\n`pollIssuesWithConfig`'s `\"label\"` branch should refuse to poll (log an error and return, same as any other misconfiguration) when `cfg.Label` is empty, rather than silently falling through to an unfiltered API call. Ideally this is also caught at config-validation time (`internal/infrastructure/configuration/validate.go`) when `dispatch.trigger` is `\"label\"` or `\"either\"` and `label` is blank.\n","status":"closed","priority":2,"issue_type":"bug","assignee":"samcharles93","created_at":"2026-08-08T16:26:41Z","updated_at":"2026-08-20T13:02:18Z","started_at":"2026-08-20T12:57:03Z","closed_at":"2026-08-20T13:02:18Z","close_reason":"Fixed in fix/label-dispatch-empty-label (31efdcf): pollIssuesWithConfig/pollEitherWithConfig now refuse the label poll when cfg.Label is empty, and validateDispatch rejects the misconfiguration at load time. Adversarially reviewed; one weak test strengthened to actually verify assignee matches survive.","external_ref":"https://github.com/samcharles93/archie-core/issues/445","source_system":"github:https://github.com/samcharles93/archie-core/issues/445:445","metadata":null,"labels":["bug"],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-1786637500980-423-12a63a68","title":"webui(chat): dynamic header content breaks the fixed no-scroll chat layout","description":"The Chat page's layout (`ui/src/chat/chat.css`) is built for a fixed, no-scroll chat window: `.chat-workspace` uses `grid-template-rows: auto minmax(0, 1fr) auto` with `overflow: hidden`, and only `.chat-transcript` (the message list) is meant to scroll. `.chat-page` only sets `min-height: calc(100vh - 5rem)`, not a fixed height.\n\nAny dynamic content injected above `.chat-layout` -- the status/error banner (see #443), extra status pills, a long \"Reload Telegram\"/\"Check updates\" row wrapping on a narrower viewport -- has no height budget accounted for, so it just pushes the whole grid down and grows total page height past the viewport. That breaks the intended design: the page itself scrolls instead of just the transcript.\n\nScreenshot: Chat page with the 501 error banner (see #443) visibly adding an extra row that isn't accounted for in the fixed layout.\n\n### Expected\n\nThe top status/banner region should have a bounded height (or the page should reserve space for it) so injecting a banner or wrapping the status pills never causes page-level scroll -- only `.chat-transcript` should ever scroll.\n","status":"closed","priority":2,"issue_type":"bug","created_at":"2026-08-08T16:17:47Z","updated_at":"2026-08-08T16:45:42Z","closed_at":"2026-08-08T16:45:43Z","external_ref":"https://github.com/samcharles93/archie-core/issues/444","source_system":"github:https://github.com/samcharles93/archie-core/issues/444:444","metadata":null,"labels":["bug"],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-1786637500953-422-01075562","title":"webui(chat): raw 501 error banner when update-check is unconfigured","description":"The Chat page shows a raw \"501 Not Implemented\" banner across the top when the release-update-check feature isn't configured. `POST /api/chat/update` correctly returns 501 when `chat.telegram.update_check_command` is unset in config (`cmd/archied/telegram_setup.go` `makeUpdateService` returns nil in that case, which is a legitimate, expected \"not configured\" state -- same category as an unconfigured channel).\n\nThe bug is in the frontend's handling of that response. `ui/src/chat/chat.js` `refreshUpdate()` is called unconditionally on page load (line ~365) with no guard, and its catch block does:\n\n```js\n} catch (err) {\n updatePanel.replaceChildren(el(\"span\", err.message || \"Updates unavailable\"));\n}\n```\n\nThis renders the raw fetch error text (including the literal HTTP status) directly into a visible page banner, rather than treating \"updates not configured\" as a quiet empty state -- the same pattern already used for an unconfigured channel on the Channels page (\"Not configured\", not an error).\n\n### Expected\n\nA 501/\"not configured\" response from `/api/chat/update` should render nothing (or a subtle \"update checks not configured\" note), not a raw HTTP error banner.\n\nScreenshot: Chat page, banner reading \"501 Not Implemented\" directly under the top status bar.\n","status":"closed","priority":2,"issue_type":"bug","created_at":"2026-08-08T16:17:37Z","updated_at":"2026-08-08T16:44:14Z","closed_at":"2026-08-08T16:44:15Z","external_ref":"https://github.com/samcharles93/archie-core/issues/443","source_system":"github:https://github.com/samcharles93/archie-core/issues/443:443","metadata":null,"labels":["bug"],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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())
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user