package server import ( "context" "fmt" "log" "reflect" "sync" "time" "git.a-wan.net/alan/pipelines/internal/chattools" "git.a-wan.net/alan/pipelines/internal/protocol" ) // show_run records a card that follows one run. Its body is the run's summary // when shown; the run event hub tells the service when a followed run changes // (observeRun), and the service rereads the run, stores the new body over the // item and pushes it to the chat. A subscribe reply rereads every followed // run too, so a card is current after a restart that lost the watches. // shownRunRefreshDelay coalesces a run's bursts of events into one reread. var shownRunRefreshDelay = 400 * time.Millisecond // runWatches maps a followed run to the items (id to session) showing it. type runWatches struct { mu sync.Mutex items map[int64]map[string]string timers map[int64]*time.Timer } func (s *chatToolService) runShowRun(ctx context.Context, runID int64, title string) (*protocol.ChatShownItem, chattools.Result) { fail := func(text string) (*protocol.ChatShownItem, chattools.Result) { return nil, chattools.Result{Text: "Nothing was shown: " + text, IsError: true} } if runID <= 0 { return fail("run_id must be a positive run number.") } if s.runs == nil { return fail("this server does not record runs.") } summary, found, err := s.runs.RunSummaryByID(ctx, runID) if err != nil { return fail(err.Error()) } if !found { return fail(fmt.Sprintf("there is no run %d.", runID)) } body := s.shownRunBody(ctx, summary) item := protocol.ChatShownItem{Kind: protocol.ChatShownRun, Title: title, Run: &body} text := fmt.Sprintf("Shown in the operator's Pipelines chat: run %d of %s, %s", runID, body.Pipeline, body.Status) if body.CurrentStage != "" && !shownRunTerminal(body.Status) { text += " at stage " + body.CurrentStage } return &item, chattools.Result{Text: text + "; the card follows the run live."} } // chatShownRunMapStore reads the graph and stage progress a run card draws // (pipeline.Store). It is optional: without it a card has no mini-map. type chatShownRunMapStore interface { RunShownMap(ctx context.Context, id int64) (*protocol.ChatShownRunMap, error) } func (s *chatToolService) shownRunBody(ctx context.Context, summary protocol.RunSummary) protocol.ChatShownRunBody { body := protocol.ChatShownRunBody{ ID: summary.ID, Pipeline: summary.Name, Title: summary.Title, Status: summary.Status, Outcome: summary.Outcome, CurrentStage: summary.CurrentStage, Workspace: summary.Workspace, StartedAt: shownRunTime(summary.CreatedAt), FinishedAt: shownRunTime(summary.FinishedAt), } if maps, ok := s.runs.(chatShownRunMapStore); ok { runMap, err := maps.RunShownMap(ctx, summary.ID) if err != nil { log.Printf("chat tools: run %d card map: %v", summary.ID, err) } body.Map = runMap } return body } func shownRunTime(value string) int64 { for _, layout := range []string{time.RFC3339, "2006-01-02 15:04:05"} { if parsed, err := time.Parse(layout, value); err == nil { return parsed.UnixMilli() } } return 0 } func shownRunTerminal(status string) bool { switch status { case "succeeded", "failed", "canceled", "interrupted": return true } return false } // watchRun follows runID for the item. func (s *chatToolService) watchRun(runID int64, sessionID, itemID string) { w := &s.watch w.mu.Lock() defer w.mu.Unlock() if w.items == nil { w.items = map[int64]map[string]string{} } if w.items[runID] == nil { w.items[runID] = map[string]string{} } w.items[runID][itemID] = sessionID } // observeRun is the run event hub's observer: a followed run's change is // reread once its burst of events settles. func (s *chatToolService) observeRun(frame protocol.RunEventFrame) { s.observeRunFollowups(frame) w := &s.watch w.mu.Lock() defer w.mu.Unlock() if len(w.items[frame.RunID]) == 0 { return } if w.timers == nil { w.timers = map[int64]*time.Timer{} } if w.timers[frame.RunID] != nil { return } runID := frame.RunID w.timers[runID] = time.AfterFunc(shownRunRefreshDelay, func() { w.mu.Lock() delete(w.timers, runID) followers := make(map[string]string, len(w.items[runID])) for id, session := range w.items[runID] { followers[id] = session } w.mu.Unlock() ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() for itemID, sessionID := range followers { if s.shown == nil { return } item, found, err := s.shown.ChatShownItem(ctx, sessionID, itemID) if err != nil || !found || item.Run == nil { s.unwatchRun(runID, itemID) continue } s.refreshRunItem(ctx, sessionID, item, true) } }) } func (s *chatToolService) unwatchRun(runID int64, itemID string) { s.watch.mu.Lock() defer s.watch.mu.Unlock() delete(s.watch.items[runID], itemID) if len(s.watch.items[runID]) == 0 { delete(s.watch.items, runID) } } // refreshRunItem rereads a run item's run; a changed body is stored and pushed // to the chat. A finished run is no longer followed. func (s *chatToolService) refreshRunItem(ctx context.Context, sessionID string, item protocol.ChatShownItem, push bool) protocol.ChatShownItem { if item.Run == nil || s.runs == nil { return item } summary, found, err := s.runs.RunSummaryByID(ctx, item.Run.ID) if err != nil || !found { return item } body := s.shownRunBody(ctx, summary) if shownRunTerminal(body.Status) { s.unwatchRun(body.ID, item.ID) } else { s.watchRun(body.ID, sessionID, item.ID) } if reflect.DeepEqual(body, *item.Run) { return item } item.Run = &body if s.shown != nil { if _, err := s.shown.ReplaceChatShownItem(ctx, sessionID, item); err != nil { log.Printf("chat tools session=%s: update run item %s: %v", sessionID, item.ID, err) return item } } if push && s.hub != nil { s.hub.fanout(sessionID, protocol.Message{Type: protocol.ChatShown, ChatShown: &protocol.ChatShownFrame{SessionID: sessionID, Items: []protocol.ChatShownItem{item}}}, "") } return item }