~james/core

core/cilogs/tui.go -rw-r--r-- 12.7 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 16 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
package cilogs

import (
	"context"
	"errors"
	"fmt"
	"strings"
	"time"

	"github.com/charmbracelet/bubbles/spinner"
	"github.com/charmbracelet/bubbles/viewport"
	tea "github.com/charmbracelet/bubbletea"
	"github.com/charmbracelet/lipgloss"
	"github.com/gorilla/websocket"
	"tangled.org/core/api/org_tangled"
	extlexutil "tangled.org/core/lexutil"
)

var (
	colorFg          lipgloss.NoColor   = lipgloss.NoColor{}
	colorBlue        lipgloss.ANSIColor = 4
	colorBrightBlack lipgloss.ANSIColor = 8
)

type tickMsg time.Time

type statusUpdateMsg struct {
	pipeline *org_tangled.CiDefs_Pipeline
}

type statusUpdateErrMsg struct{ err error }

type pipelineModel struct {
	renderer *lipgloss.Renderer
	xrpcc    *extlexutil.Client
	pipeline *org_tangled.CiDefs_Pipeline
	selected int
	logs     map[string]*workflowLogs

	// pipeline log stream: cancel tears down the consumer goroutine on quit.
	// the event/done channels are threaded through log messages, not stored here.
	cancel     context.CancelFunc
	streamDone bool
	streamErr  error

	spinner spinner.Model
	width   int
	height  int
}

type workflowLogs struct {
	steps     []step
	stepIndex map[int64]int // stepId -> index map
	vp        viewport.Model
	ready     bool
}

func newPipelineModel(renderer *lipgloss.Renderer, xrpcc *extlexutil.Client, pipeline *org_tangled.CiDefs_Pipeline, width, height int) *pipelineModel {
	logs := make(map[string]*workflowLogs, len(pipeline.Workflows))
	for _, wf := range pipeline.Workflows {
		logs[workflowName(wf)] = &workflowLogs{stepIndex: make(map[int64]int)}
	}
	sp := spinner.New(spinner.WithSpinner(spinner.Line))
	return &pipelineModel{
		renderer: renderer,
		xrpcc:    xrpcc,
		pipeline: pipeline,
		logs:     logs,
		spinner:  sp,
		width:    width,
		height:   height,
	}
}

func (m *pipelineModel) Init() tea.Cmd {
	return tea.Batch(tick(), m.spinner.Tick, m.subscribeCmd())
}

func tick() tea.Cmd {
	return tea.Tick(time.Second, func(t time.Time) tea.Msg { return tickMsg(t) })
}

// subscribeCmd opens the ci.pipeline.subscribeLogs stream for current pipeline.
// A consumer goroutine pushes decoded events onto the scheduler channel; the
// returned command yields the first event into the bubbletea loop.
func (m *pipelineModel) subscribeCmd() tea.Cmd {
	// cancel existing subscriptions just in case
	if m.cancel != nil {
		m.cancel()
	}
	sched := newEventScheduler()
	done := make(chan error, 1)
	ctx, cancel := context.WithCancel(context.Background())
	m.cancel = cancel

	repo, pipelineId := m.pipeline.Repo, m.pipeline.Id
	go func() {
		err := org_tangled.CiSubscribePipelineLogs(ctx, m.xrpcc, repo, pipelineId, nil, sched)
		done <- err
	}()

	return readEventCmd(sched.ch, done)
}

func readEventCmd(events chan *org_tangled.CiSubscribePipelineLogs_Event, done chan error) tea.Cmd {
	return func() tea.Msg {
		ev, ok := <-events
		if !ok {
			return logDoneMsg{err: <-done}
		}
		return logEventMsg{ev: ev, events: events, done: done}
	}
}

// fetchStatusCmd re-fetches the pipeline
func (m *pipelineModel) fetchStatusCmd() tea.Cmd {
	repo, pipelineId := m.pipeline.Repo, m.pipeline.Id
	return func() tea.Msg {
		ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
		defer cancel()
		out, err := org_tangled.CiGetPipeline(ctx, m.xrpcc, pipelineId, repo)
		if err != nil {
			return statusUpdateErrMsg{err: fmt.Errorf("refreshing pipeline: %w", err)}
		}
		return statusUpdateMsg{pipeline: out}
	}
}

func (m *pipelineModel) vpHeight() int {
	return max(m.height-2, 1) // topbar + empty line take 2 lines
}

// resizeViewports updates all viewport dimensions and re-renders their content after a terminal resize.
//
// TODO: can be tedious if we have logs of logs
func (m *pipelineModel) resizeViewports() {
	for _, wl := range m.logs {
		if !wl.ready {
			continue
		}
		atBottom := wl.vp.AtBottom()
		wl.vp.Width = m.width
		wl.vp.Height = m.vpHeight()
		wl.vp.SetContent(renderLogs(m.renderer, wl, m.width))
		if atBottom {
			wl.vp.GotoBottom()
		}
	}
}

func (m *pipelineModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	switch msg := msg.(type) {
	case tea.WindowSizeMsg:
		m.width, m.height = msg.Width, msg.Height
		m.resizeViewports()

	case tickMsg:
		// re-render running workflows so elapsed times advance
		m.refreshRunning()
		return m, tick()

	case spinner.TickMsg:
		var cmd tea.Cmd
		m.spinner, cmd = m.spinner.Update(msg)
		return m, cmd

	case tea.KeyMsg:
		switch msg.String() {
		case "q", "ctrl+c":
			if m.cancel != nil {
				m.cancel()
			}
			return m, tea.Quit
		case "tab", "right", "l":
			m.selected = (m.selected + 1) % len(m.pipeline.Workflows)
			return m, nil
		case "shift+tab", "left", "h":
			m.selected = (m.selected - 1 + len(m.pipeline.Workflows)) % len(m.pipeline.Workflows)
			return m, nil
		}
		if wl := m.selectedLogs(); wl != nil && wl.ready {
			switch msg.String() {
			case "g":
				wl.vp.GotoTop()
				return m, nil
			case "G":
				wl.vp.GotoBottom()
				return m, nil
			case "ctrl+e":
				wl.vp.ScrollDown(1)
				return m, nil
			case "ctrl+y":
				wl.vp.ScrollUp(1)
				return m, nil
			}
			var cmd tea.Cmd
			wl.vp, cmd = wl.vp.Update(msg)
			return m, cmd
		}

	case logEventMsg:
		m.applyEvent(msg.ev)
		return m, readEventCmd(msg.events, msg.done)

	case logDoneMsg:
		m.streamDone = true
		if !isExpectedClose(msg.err) {
			m.streamErr = msg.err
		}
		m.refreshAll()
		// resolve final workflow statuses once now that the stream has ended
		return m, m.fetchStatusCmd()

	case statusUpdateMsg:
		m.pipeline = msg.pipeline
		known := make(map[string]bool, len(m.pipeline.Workflows))
		for _, wf := range m.pipeline.Workflows {
			known[workflowName(wf)] = true
		}
		for name := range m.logs {
			if !known[name] {
				delete(m.logs, name)
			}
		}
		if m.selected >= len(m.pipeline.Workflows) {
			m.selected = max(len(m.pipeline.Workflows)-1, 0)
		}
		m.refreshAll()

	case statusUpdateErrMsg:
		// best-effort final status refresh; ignore failures
	}

	return m, nil
}

func (m *pipelineModel) selectedLogs() *workflowLogs {
	if len(m.pipeline.Workflows) < 1+m.selected {
		return nil
	}
	return m.logs[workflowName(m.pipeline.Workflows[m.selected])]
}

func (m *pipelineModel) initViewport(wl *workflowLogs) {
	if wl.ready {
		return
	}
	wl.vp = viewport.New(m.width, m.vpHeight())
	wl.ready = true
}

// ensureWorkflow returns the log state for a workflow, lazily creating its routing entry.
func (m *pipelineModel) ensureWorkflow(name string) *workflowLogs {
	wl, ok := m.logs[name]
	if !ok {
		wl = &workflowLogs{stepIndex: make(map[int64]int)}
		m.logs[name] = wl
	}
	return wl
}

// renderWorkflow re-renders a workflow's viewport, preserving bottom-stickiness.
func (m *pipelineModel) renderWorkflow(wl *workflowLogs) {
	m.initViewport(wl)
	atBottom := wl.vp.AtBottom()
	wl.vp.SetContent(renderLogs(m.renderer, wl, m.width))
	if atBottom {
		wl.vp.GotoBottom()
	}
}

// refreshAll re-renders every initialized viewport.
func (m *pipelineModel) refreshAll() {
	for _, wl := range m.logs {
		m.renderWorkflow(wl)
	}
}

// refreshRunning re-renders workflows with unfinished steps so elapsed times advance.
func (m *pipelineModel) refreshRunning() {
	if m.streamDone {
		return
	}
	for _, wl := range m.logs {
		if !wl.ready {
			continue
		}
		for i := range wl.steps {
			if !wl.steps[i].finished {
				m.renderWorkflow(wl)
				break
			}
		}
	}
}

// applyEvent routes a decoded subscribeLogs event into the matching workflow.
func (m *pipelineModel) applyEvent(ev *org_tangled.CiSubscribePipelineLogs_Event) {
	switch {
	case ev.Error != nil:
		if ev.Error.Message != "" {
			m.streamErr = fmt.Errorf("%s: %s", ev.Error.Error, ev.Error.Message)
		} else {
			m.streamErr = fmt.Errorf("%s", ev.Error.Error)
		}

	case ev.Control != nil:
		c := ev.Control
		wl := m.ensureWorkflow(c.Workflow)
		switch derefStr(c.Status) {
		case "start":
			wl.stepIndex[c.Step] = len(wl.steps)
			wl.steps = append(wl.steps, step{
				id: c.Step, name: c.Content, command: derefStr(c.Command), startTime: parseRFC3339(c.Time),
			})
		case "end":
			if idx, ok := wl.stepIndex[c.Step]; ok {
				wl.steps[idx].endTime, wl.steps[idx].finished = parseRFC3339(c.Time), true
			}
		}
		m.renderWorkflow(wl)

	case ev.Data != nil:
		d := ev.Data
		wl := m.ensureWorkflow(d.Workflow)
		if idx, ok := wl.stepIndex[d.Step]; ok {
			wl.steps[idx].lines = append(wl.steps[idx].lines, d.Content)
		}
		m.renderWorkflow(wl)
	}
}

// isExpectedClose reports whether err is a clean websocket close (or nil).
func isExpectedClose(err error) bool {
	if err == nil {
		return true
	}
	var ce *websocket.CloseError
	if errors.As(err, &ce) {
		switch ce.Code {
		case websocket.CloseNormalClosure, websocket.CloseGoingAway, websocket.CloseAbnormalClosure:
			return true
		}
	}
	return false
}

// renderLogs builds the full log content string for a workflow, used as viewport content.
func renderLogs(r *lipgloss.Renderer, wl *workflowLogs, width int) string {
	headerStyle := r.NewStyle().Foreground(colorFg).Bold(true)
	cmdStyle := r.NewStyle().Foreground(colorBlue).Width(width)
	dimStyle := r.NewStyle().Faint(true)
	var sb strings.Builder
	for i := range wl.steps {
		st := &wl.steps[i]
		dur := ""
		if st.finished {
			dur = st.endTime.Sub(st.startTime).Round(time.Millisecond).String()
		} else if !st.startTime.IsZero() {
			dur = time.Since(st.startTime).Round(time.Second).String()
		}
		// build overlay: "── name ──...── dur ──"
		nameStr := headerStyle.Render(st.name + " ")
		durStr := headerStyle.Render(" " + dur + " ")
		nameW := lipgloss.Width(nameStr)
		durW := lipgloss.Width(durStr)
		fillW := max(width-nameW-durW, 0)
		fill := dimStyle.Render(strings.Repeat("─", fillW))
		header := nameStr + fill + durStr
		sb.WriteString(header + "\n")
		if st.command != "" {
			sb.WriteString(cmdStyle.Render(st.command) + "\n")
		}
		for _, l := range st.lines {
			sb.WriteString(l + "\n")
		}
		sb.WriteString("\n")
	}
	return sb.String()
}

func (m *pipelineModel) View() string {
	body := ""
	if wl := m.selectedLogs(); wl != nil && wl.ready {
		body = wl.vp.View()
	}
	if m.streamErr != nil {
		body = lipgloss.JoinVertical(lipgloss.Left, body, m.renderer.NewStyle().Foreground(colorBlue).Render("stream error: "+m.streamErr.Error()))
	}
	return lipgloss.JoinVertical(lipgloss.Left, m.topbarView(), "", body)
}

// topbarView renders the single-line tab bar with workflow tabs left and trigger info + help right.
func (m *pipelineModel) topbarView() string {
	r := m.renderer
	activeStyle := r.NewStyle().Background(colorBlue).Foreground(colorFg).Bold(true)

	now := time.Now()

	var tabs strings.Builder
	for i, wf := range m.pipeline.Workflows {
		status := wf.Status
		elapsed := workflowElapsed(wf, now).Round(time.Second).String()
		base := " " + statusIcon(status, m.spinner.View()) + " " + workflowName(wf)
		if i == m.selected {
			tab := base
			if elapsed != "" {
				tab += " " + elapsed
			}
			tab += " "
			tabs.WriteString(activeStyle.Render(tab))
		} else {
			tabs.WriteString(base)
			if elapsed != "" {
				dim := r.NewStyle().Faint(true)
				tabs.WriteString(" " + dim.Render(elapsed))
			}
			tabs.WriteString(" ")
		}
	}

	tabsStr := tabs.String()
	infoStr := triggerLine(r, m.pipeline.Trigger, m.pipeline.Commit) + " · " + helpText(r)

	gap := max(m.width-lipgloss.Width(tabsStr)-lipgloss.Width(infoStr), 1)

	return tabsStr + strings.Repeat(" ", gap) + infoStr
}

func helpText(r *lipgloss.Renderer) string {
	key := r.NewStyle().Foreground(colorFg)
	action := r.NewStyle().Faint(true)
	sep := action.Render(" · ")

	items := []string{
		key.Render("←/→") + " " + action.Render("switch"),
		key.Render("↑/↓") + " " + action.Render("scroll"),
		key.Render("q") + " " + action.Render("quit"),
	}
	return strings.Join(items, sep)
}

func shortSha(sha string) string {
	if len(sha) >= 8 {
		return sha[:8]
	}
	return sha
}

func triggerLine(r *lipgloss.Renderer, t *org_tangled.CiDefs_Pipeline_Trigger, sha string) string {
	hash := shortSha(sha)
	dim := r.NewStyle().Faint(true)
	if t == nil {
		return dim.Render(hash)
	}
	switch {
	case t.EventPush != nil:
		return t.EventPush.Ref + dim.Render("@"+hash) + dim.Render(" (push)")
	case t.EventPullRequest != nil:
		pr := t.EventPullRequest
		return derefStr(pr.TargetBranch) + dim.Render(" <- "+derefStr(pr.SourceBranch)+"@"+hash) + dim.Render(" (pull-request)")
	case t.CiTriggerSchedule != nil:
		return t.CiTriggerSchedule.Ref + dim.Render("@"+hash) + dim.Render(" (schedule)")
	}
	return dim.Render(hash)
}

func statusIcon(status string, spinnerFrame string) string {
	switch status {
	case "success":
		return "✓"
	case "failed":
		return "×"
	case "running":
		return spinnerFrame
	case "pending":
		return "·"
	case "timeout":
		return "⌀"
	case "cancelled":
		return "-"
	default:
		return "?"
	}
}

func derefStr(s *string) string {
	if s == nil {
		return ""
	}
	return *s
}

func parseRFC3339(s string) time.Time {
	t, err := time.Parse(time.RFC3339, s)
	if err != nil {
		return time.Time{}
	}
	return t
}