BlueGit

timfa bluegit

Files

bluegit / internal / server / pipeline_page.go

pipeline_page.go

pipeline_page.go 20.8 KiB Download Raw
1package server
2
3import (
4 "bytes"
5 "encoding/json"
6 "net/http"
7 "net/url"
8 "strconv"
9 "strings"
10 "time"
11
12 "gitlab.com/Timfa/bluegit/internal/access"
13 "gitlab.com/Timfa/bluegit/internal/ci"
14 "gitlab.com/Timfa/bluegit/internal/i18n"
15 "gitlab.com/Timfa/bluegit/internal/store"
16)
17
18// PipeRow is één rij in het pipeline-overzicht.
19type PipeRow struct {
20 ID int64
21 Status string
22 Label string
23 Duration string
24 When string
25 Title string
26 SHA string
27 Short string
28 Ref string
29 RefKind string
30 Source string
31 SourceLabel string
32 MRNumber int64
33 Actor string
34 ActorURL string
35 Avatar string
36 Initial string
37 Stages []StageView
38 Failed bool
39 Live bool
40}
41
42// StageView is één bolletje in de stages-kolom.
43type StageView struct {
44 Name string
45 Status string
46 Label string
47 Tip string
48 Jobs []JobLink
49}
50
51// JobLink is een job in een stage-popover of in de zijbalk.
52type JobLink struct {
53 ID int64
54 Name string
55 Status string
56 Label string
57 Queue string
58 Current bool
59 Stage string
60}
61
62// JobPage is de console van één job.
63type JobPage struct {
64 Job store.Job
65 Pipe store.Pipeline
66 Name string
67 Status string
68 Label string
69 Actor string
70 ActorURL string
71 Avatar string
72 Initial string
73 When string
74 Duration string
75 Finished string
76 Queued string
77 Timeout string
78 Source string
79 Ref string
80 RefKind string
81 Short string
82 Title string
83 Stage string
84 PipeStatus string
85 PipeLabel string
86 Stages []string
87 Related []JobLink
88 Blocks []LogBlock
89 Running bool
90 LogBytes int
91 CanPlay bool
92 Environment string
93 EnvironmentURL string
94 EnvironmentLink string
95 Queue string
96}
97
98// LogBlock is een losse regel of een inklapbare sectie.
99type LogBlock struct {
100 Section bool
101 Title string
102 Duration string
103 Open bool
104 Lines []LogLine
105}
106
107// LogLine is één regel in de console.
108type LogLine struct {
109 N int
110 Time string
111 Text string
112 Spans []LogSpan
113}
114
115func (s *Server) fillPipelines(r *http.Request, v *View, repo store.Repo) {
116 lang := s.langOf(r)
117 list, _ := s.Store.ListPipelines(r.Context(), repo.ID)
118 q := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("q")))
119 v.Query = r.URL.Query().Get("q")
120 ranks := s.queueRanks(r.Context())
121 users := map[string]store.User{}
122 for _, p := range list {
123 row := s.pipeRow(r, lang, repo, p, users, ranks)
124 if q != "" && !pipeMatches(row, q) {
125 continue
126 }
127 if rowLive(row) {
128 v.Live = true
129 }
130 v.PipeRows = append(v.PipeRows, row)
131 }
132 v.LiveURL = repoURL(repo) + "/-/pipelines"
133 if raw := strings.TrimSpace(r.URL.Query().Get("q")); raw != "" {
134 v.LiveURL += "?q=" + url.QueryEscape(raw)
135 }
136}
137
138func rowLive(row PipeRow) bool {
139 if row.Status == "pending" || row.Status == "running" {
140 return true
141 }
142 for _, st := range row.Stages {
143 if st.Status == "pending" || st.Status == "running" {
144 return true
145 }
146 for _, j := range st.Jobs {
147 if j.Status == "pending" || j.Status == "running" {
148 return true
149 }
150 }
151 }
152 return false
153}
154
155func (s *Server) pipeRow(r *http.Request, lang i18n.Lang, repo store.Repo, p store.Pipeline, users map[string]store.User, ranks map[int64]int) PipeRow {
156 jobs, _ := s.Store.JobsByPipeline(r.Context(), p.ID)
157 name, kind := ci.SplitRef(p.Ref)
158 status := displayStatus(s.pipeStatusFor(p), jobs)
159 actor, avatar, actorURL := s.actorOf(r, p.Actor, users)
160 initial := ""
161 if actor != "" {
162 initial = strings.ToUpper(actor[:1])
163 }
164 sourceLabel, mrNumber := s.pipelineSourceLabel(r, repo, p)
165 row := PipeRow{
166 ID: p.ID, Status: status, Label: s.tr(r, "pipe."+status),
167 Duration: pipelineClock(p), When: i18n.Ago(lang, p.CreatedAt.Unix()),
168 Title: p.CommitTitle, SHA: p.CommitSHA, Short: shortSHA(p.CommitSHA),
169 Ref: name, RefKind: kind, Source: p.Source, SourceLabel: sourceLabel, MRNumber: mrNumber,
170 Actor: actor, ActorURL: actorURL, Avatar: avatar, Initial: initial,
171 Stages: stageViews(jobs, ranks, func(key string, args ...any) string { return s.tr(r, key, args...) }),
172 Failed: jobsFailed(jobs),
173 }
174 row.Live = rowLive(row)
175 return row
176}
177
178func jobsFailed(jobs []store.Job) bool {
179 for _, j := range jobs {
180 if j.Status == "failed" {
181 return true
182 }
183 }
184 return false
185}
186
187// pipelineSourceLabel benoemt een pipeline die bij een merge request hoort,
188// ook wanneer de rij als push is gestart en daarna gekoppeld is.
189// Een gewone push zonder merge request krijgt geen extra label.
190func (s *Server) pipelineSourceLabel(r *http.Request, repo store.Repo, p store.Pipeline) (string, int64) {
191 if p.MRID != 0 {
192 var number int64
193 if mr, err := s.Store.MergeRequest(r.Context(), repo.ID, p.MRID); err == nil {
194 number = mr.Number
195 }
196 return s.tr(r, "pipe.src.merge_request_event"), number
197 }
198 if p.Source == "" || p.Source == "push" {
199 return "", 0
200 }
201 key := "pipe.src." + p.Source
202 label := s.tr(r, key)
203 if label == key {
204 label = p.Source
205 }
206 return label, 0
207}
208
209func (s *Server) pipelineSourceText(r *http.Request, repo store.Repo, p store.Pipeline) string {
210 label, number := s.pipelineSourceLabel(r, repo, p)
211 if label == "" {
212 return ""
213 }
214 if number == 0 {
215 return label
216 }
217 return label + " !" + strconv.FormatInt(number, 10)
218}
219
220func (s *Server) actorOf(r *http.Request, name string, cache map[string]store.User) (string, string, string) {
221 name = strings.TrimSpace(name)
222 if name == "" {
223 return "", "", ""
224 }
225 u, ok := cache[name]
226 if !ok {
227 found, err := s.Store.UserByUsername(r.Context(), name)
228 if err == nil {
229 u = found
230 }
231 cache[name] = u
232 }
233 if u.ID == 0 {
234 return name, "", ""
235 }
236 return u.Username, u.AvatarURL, "/users/" + u.Username
237}
238
239func pipeMatches(row PipeRow, q string) bool {
240 bits := []string{row.Label, row.Title, row.SHA, row.Short, row.Ref, row.Actor, row.SourceLabel, strconv.FormatInt(row.ID, 10), row.Status}
241 for _, st := range row.Stages {
242 bits = append(bits, st.Name)
243 for _, j := range st.Jobs {
244 bits = append(bits, j.Name)
245 }
246 }
247 for _, b := range bits {
248 if strings.Contains(strings.ToLower(b), q) {
249 return true
250 }
251 }
252 return false
253}
254
255func displayStatus(pipe string, jobs []store.Job) string {
256 switch pipe {
257 case "failed":
258 return "failed"
259 case "running":
260 return "running"
261 case "manual":
262 return "manual"
263 case "queued":
264 return "pending"
265 case "canceled":
266 return "canceled"
267 case "waiting_for_update":
268 return "waiting_for_update"
269 }
270 warn := false
271 for _, j := range jobs {
272 if j.Status == "failed" && j.AllowFailure {
273 warn = true
274 }
275 }
276 if warn {
277 return "warning"
278 }
279 if pipe == "success" {
280 return "passed"
281 }
282 if pipe == "" {
283 return "pending"
284 }
285 return pipe
286}
287
288func stageViews(jobs []store.Job, ranks map[int64]int, tr func(string, ...any) string) []StageView {
289 var order []string
290 by := map[string][]store.Job{}
291 for _, j := range jobs {
292 if _, ok := by[j.Stage]; !ok {
293 order = append(order, j.Stage)
294 }
295 by[j.Stage] = append(by[j.Stage], j)
296 }
297 var out []StageView
298 for _, name := range order {
299 group := by[name]
300 status := stageStatus(group)
301 label := tr("pipe." + status)
302 var links []JobLink
303 for _, j := range group {
304 st := jobDisplay(j)
305 links = append(links, JobLink{
306 ID: j.ID, Name: j.Name, Status: st, Label: tr("pipe." + st), Stage: j.Stage,
307 Queue: queueText(tr, ranks, j.ID),
308 })
309 }
310 out = append(out, StageView{Name: name, Status: status, Label: label, Tip: name + ": " + strings.ToLower(label), Jobs: links})
311 }
312 return out
313}
314
315func stageStatus(jobs []store.Job) string {
316 pending, failed, warning, running, canceled := false, false, false, false, false
317 seen := false
318 for _, j := range jobs {
319 seen = true
320 switch {
321 case j.Status == "running":
322 running = true
323 case j.Status == "failed" && !j.AllowFailure:
324 failed = true
325 case j.Status == "canceled" && !j.AllowFailure:
326 canceled = true
327 case j.Status == "failed" && j.AllowFailure:
328 warning = true
329 case j.Status == "queued" || j.Status == "manual":
330 pending = true
331 }
332 }
333 if !seen {
334 return "skipped"
335 }
336 if running {
337 return "running"
338 }
339 if failed {
340 return "failed"
341 }
342 if canceled {
343 return "canceled"
344 }
345 if warning {
346 return "warning"
347 }
348 if pending {
349 return "pending"
350 }
351 allSkip := true
352 for _, j := range jobs {
353 if j.Status != "skipped" {
354 allSkip = false
355 }
356 }
357 if allSkip {
358 return "skipped"
359 }
360 return "passed"
361}
362
363func jobDisplay(j store.Job) string {
364 if j.Status == "failed" && j.AllowFailure {
365 return "warning"
366 }
367 switch j.Status {
368 case "success":
369 return "passed"
370 case "queued":
371 return "pending"
372 case "":
373 return "pending"
374 default:
375 return j.Status
376 }
377}
378
379func pipelineClock(p store.Pipeline) string {
380 end := p.FinishedAt
381 if end.IsZero() {
382 end = time.Now()
383 }
384 start := p.StartedAt
385 if start.IsZero() {
386 start = p.CreatedAt
387 }
388 if start.IsZero() {
389 return ""
390 }
391 return formatClock(end.Sub(start))
392}
393
394func formatClock(d time.Duration) string {
395 if d < 0 {
396 d = 0
397 }
398 s := int(d.Seconds())
399 return pad2(s/3600) + ":" + pad2((s%3600)/60) + ":" + pad2(s%60)
400}
401
402func pad2(n int) string {
403 if n < 10 {
404 return "0" + strconv.Itoa(n)
405 }
406 return strconv.Itoa(n)
407}
408
409func shortSHA(sha string) string {
410 if len(sha) > 8 {
411 return sha[:8]
412 }
413 return sha
414}
415
416func (s *Server) showJob(w http.ResponseWriter, r *http.Request) {
417 _, repo, role, ok := s.guard(w, r, access.RoleReadonly)
418 if !ok {
419 return
420 }
421 p, job, ok := s.jobFromRequest(w, r, repo)
422 if !ok {
423 return
424 }
425 v := s.repoView(w, r, repo, role, job.Name)
426 v.Wide = true
427 v.Page = "pipelines"
428 v.Pipe = &p
429 v.JobPage = s.jobPage(r, repo, p, job, role)
430 s.render(w, "job", v)
431}
432
433func (s *Server) jobLog(w http.ResponseWriter, r *http.Request) {
434 _, repo, _, ok := s.guard(w, r, access.RoleReadonly)
435 if !ok {
436 return
437 }
438 _, job, ok := s.jobFromRequest(w, r, repo)
439 if !ok {
440 return
441 }
442 if r.URL.Query().Get("raw") == "1" {
443 w.Header().Set("Content-Type", "text/plain; charset=utf-8")
444 _, _ = w.Write([]byte(job.Log))
445 return
446 }
447 offset, _ := strconv.Atoi(r.URL.Query().Get("offset"))
448 if offset < 0 || offset > len(job.Log) {
449 offset = 0
450 }
451 queue := ""
452 if job.Status == "queued" {
453 tr := func(key string, args ...any) string { return s.tr(r, key, args...) }
454 queue = queueText(tr, s.queueRanks(r.Context()), job.ID)
455 }
456 w.Header().Set("Content-Type", "application/json")
457 w.Header().Set("Cache-Control", "no-store")
458 _ = json.NewEncoder(w).Encode(map[string]any{
459 "offset": len(job.Log),
460 "status": job.Status,
461 "text": job.Log[offset:],
462 "queue": queue,
463 })
464}
465
466func (s *Server) retryPipeline(w http.ResponseWriter, r *http.Request) {
467 u, repo, _, ok := s.guard(w, r, access.RoleDeveloper)
468 if !ok || !s.csrfOK(w, r) {
469 return
470 }
471 id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
472 if err != nil {
473 http.NotFound(w, r)
474 return
475 }
476 back := safeRepoBack(repo, r.FormValue("back"))
477 if back == "" {
478 back = repoURL(repo) + "/-/pipelines/" + strconv.FormatInt(id, 10)
479 }
480 newID, err := s.opRetryPipeline(r.Context(), u, repo, id, r.FormValue("mode"))
481 if !s.uiOK(w, r, back, err) {
482 return
483 }
484 dest := back
485 if r.FormValue("mode") == "all" {
486 dest = repoURL(repo) + "/-/pipelines/" + strconv.FormatInt(newID, 10)
487 }
488 s.redirect(w, r, dest, s.tr(r, "flash.pipeRetry"), "")
489}
490
491func safeRepoBack(repo store.Repo, back string) string {
492 back = strings.TrimSpace(back)
493 prefix := "/" + repo.FullPath()
494 if back != prefix && !strings.HasPrefix(back, prefix+"/") {
495 return ""
496 }
497 if strings.Contains(back, "..") || strings.Contains(back, "\\") || strings.Contains(back, "\n") || strings.Contains(back, "?") {
498 return ""
499 }
500 return back
501}
502
503func (s *Server) playJob(w http.ResponseWriter, r *http.Request) {
504 u, repo, _, ok := s.guard(w, r, access.RoleDeveloper)
505 if !ok || !s.csrfOK(w, r) {
506 return
507 }
508 p, job, ok := s.jobFromRequest(w, r, repo)
509 if !ok {
510 return
511 }
512 _, _ = s.opJobAction(r.Context(), u, repo, p.ID, job.ID, "play")
513 s.redirect(w, r, repoURL(repo)+"/-/pipelines/"+strconv.FormatInt(p.ID, 10)+"/jobs/"+strconv.FormatInt(job.ID, 10), s.tr(r, "flash.pipeline"), "")
514}
515
516func (s *Server) jobFromRequest(w http.ResponseWriter, r *http.Request, repo store.Repo) (store.Pipeline, store.Job, bool) {
517 pid, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
518 if err != nil {
519 http.NotFound(w, r)
520 return store.Pipeline{}, store.Job{}, false
521 }
522 jid, err := strconv.ParseInt(r.PathValue("job"), 10, 64)
523 if err != nil {
524 http.NotFound(w, r)
525 return store.Pipeline{}, store.Job{}, false
526 }
527 p, err := s.Store.PipelineByID(r.Context(), repo.ID, pid)
528 if err != nil {
529 http.NotFound(w, r)
530 return store.Pipeline{}, store.Job{}, false
531 }
532 jobs, _ := s.Store.JobsByPipeline(r.Context(), p.ID)
533 for _, j := range jobs {
534 if j.ID == jid {
535 return p, j, true
536 }
537 }
538 http.NotFound(w, r)
539 return store.Pipeline{}, store.Job{}, false
540}
541
542func (s *Server) jobPage(r *http.Request, repo store.Repo, p store.Pipeline, job store.Job, role access.Role) *JobPage {
543 lang := s.langOf(r)
544 jobs, _ := s.Store.JobsByPipeline(r.Context(), p.ID)
545 users := map[string]store.User{}
546 actor, avatar, actorURL := s.actorOf(r, p.Actor, users)
547 initial := ""
548 if actor != "" {
549 initial = strings.ToUpper(actor[:1])
550 }
551 name, kind := ci.SplitRef(p.Ref)
552 status := jobDisplay(job)
553 pipeStatus := displayStatus(s.pipeStatusFor(p), jobs)
554 end := job.FinishedAt
555 if end.IsZero() && (job.Status == "success" || job.Status == "failed" || job.Status == "skipped") {
556 end = p.FinishedAt
557 }
558 start := job.StartedAt
559 dur := ""
560 if !start.IsZero() {
561 until := end
562 if until.IsZero() {
563 until = time.Now()
564 }
565 dur = formatClock(until.Sub(start))
566 }
567 queued := ""
568 if !start.IsZero() && !p.CreatedAt.IsZero() {
569 queued = formatClock(start.Sub(p.CreatedAt))
570 }
571 timeout := formatClock(job.Timeout)
572 if job.Timeout == 0 && s.Cfg.CI.TimeoutSec > 0 {
573 timeout = formatClock(time.Duration(s.Cfg.CI.TimeoutSec) * time.Second)
574 }
575 finished := ""
576 if !end.IsZero() {
577 finished = i18n.Ago(lang, end.Unix())
578 }
579 ranks := s.queueRanks(r.Context())
580 tr := func(key string, args ...any) string { return s.tr(r, key, args...) }
581 var stages []string
582 seen := map[string]bool{}
583 var related []JobLink
584 for _, j := range jobs {
585 if !seen[j.Stage] {
586 seen[j.Stage] = true
587 stages = append(stages, j.Stage)
588 }
589 st := jobDisplay(j)
590 related = append(related, JobLink{
591 ID: j.ID, Name: j.Name, Status: st, Label: tr("pipe." + st), Current: j.ID == job.ID, Stage: j.Stage,
592 Queue: queueText(tr, ranks, j.ID),
593 })
594 }
595 sourceKey := "pipe.src." + p.Source
596 source := s.tr(r, sourceKey)
597 if source == sourceKey {
598 source = p.Source
599 }
600 return &JobPage{
601 Job: job, Pipe: p, Name: job.Name, Status: status, Label: s.tr(r, "pipe."+status),
602 Actor: actor, ActorURL: actorURL, Avatar: avatar, Initial: initial, When: i18n.Ago(lang, p.CreatedAt.Unix()),
603 Duration: dur, Finished: finished, Queued: queued, Timeout: timeout, Source: source,
604 Ref: name, RefKind: kind, Short: shortSHA(p.CommitSHA), Title: p.CommitTitle, Stage: job.Stage,
605 PipeStatus: pipeStatus, PipeLabel: s.tr(r, "pipe."+pipeStatus),
606 Stages: stages, Related: related, Blocks: parseLog(job.Log), Running: job.Status == "running" || job.Status == "queued",
607 LogBytes: len(job.Log), CanPlay: job.Status == "manual" && role.CanWriteCode(),
608 Queue: queueText(tr, ranks, job.ID),
609 Environment: job.Environment, EnvironmentURL: job.EnvironmentURL, EnvironmentLink: safeEnvironmentURL(job.EnvironmentURL),
610 }
611}
612
613func safeEnvironmentURL(raw string) string {
614 if strings.Contains(raw, "$") {
615 return ""
616 }
617 if strings.HasPrefix(raw, "https://") || strings.HasPrefix(raw, "http://") {
618 return raw
619 }
620 return ""
621}
622
623func parseLog(raw string) []LogBlock {
624 var blocks []LogBlock
625 var cur *LogBlock
626 n := 0
627 flush := func() {
628 if cur == nil {
629 return
630 }
631 blocks = append(blocks, *cur)
632 cur = nil
633 }
634 for _, row := range strings.Split(raw, "\n") {
635 if row == "" {
636 continue
637 }
638 ts, text := row, row
639 if i := strings.IndexByte(row, '\t'); i >= 0 {
640 ts, text = row[:i], row[i+1:]
641 }
642 if strings.HasPrefix(text, "section_start:") {
643 flush()
644 body := strings.TrimPrefix(text, "section_start:")
645 title := body
646 if i := strings.IndexByte(body, ':'); i >= 0 {
647 title = body[i+1:]
648 }
649 cur = &LogBlock{Section: true, Title: title, Open: true}
650 continue
651 }
652 if strings.HasPrefix(text, "section_end:") {
653 dur := ""
654 body := strings.TrimPrefix(text, "section_end:")
655 if i := strings.IndexByte(body, '\t'); i >= 0 {
656 dur = body[i+1:]
657 }
658 if cur != nil {
659 cur.Duration = dur
660 flush()
661 }
662 continue
663 }
664 n++
665 line := LogLine{N: n, Time: clockOf(ts), Text: text, Spans: ansiSpans(text)}
666 if cur != nil {
667 cur.Lines = append(cur.Lines, line)
668 continue
669 }
670 blocks = append(blocks, LogBlock{Lines: []LogLine{line}})
671 }
672 if cur != nil {
673 flush()
674 }
675 return blocks
676}
677
678func wantsJSON(r *http.Request) bool {
679 return strings.Contains(r.Header.Get("Accept"), "application/json")
680}
681
682func jobsLive(pipe string, jobs []store.Job) bool {
683 if pipe == "queued" || pipe == "running" {
684 return true
685 }
686 for _, j := range jobs {
687 if j.Status == "queued" || j.Status == "running" {
688 return true
689 }
690 }
691 return false
692}
693
694func linksFor(jobs []store.Job, ranks map[int64]int, tr func(string, ...any) string) []JobLink {
695 out := make([]JobLink, 0, len(jobs))
696 for _, j := range jobs {
697 st := jobDisplay(j)
698 out = append(out, JobLink{
699 ID: j.ID, Name: j.Name, Status: st, Label: tr("pipe." + st), Stage: j.Stage,
700 Queue: queueText(tr, ranks, j.ID),
701 })
702 }
703 return out
704}
705
706func (s *Server) partial(name string, v View) string {
707 var buf bytes.Buffer
708 tmpl := s.byLang[v.Lang]
709 if tmpl == nil {
710 tmpl = s.tmpl
711 }
712 if tmpl == nil {
713 return ""
714 }
715 if err := tmpl.ExecuteTemplate(&buf, name, v); err != nil && s.Log != nil {
716 s.Log.Error("sjabloon", "name", name, "err", err)
717 }
718 return buf.String()
719}
720
721func (s *Server) writePipeList(w http.ResponseWriter, v View) {
722 type job struct {
723 ID int64 `json:"id"`
724 Name string `json:"name"`
725 Status string `json:"status"`
726 Label string `json:"label"`
727 Queue string `json:"queue"`
728 }
729 type stage struct {
730 Name string `json:"name"`
731 Status string `json:"status"`
732 Tip string `json:"tip"`
733 Jobs []job `json:"jobs"`
734 }
735 type row struct {
736 ID int64 `json:"id"`
737 Status string `json:"status"`
738 Label string `json:"label"`
739 Duration string `json:"duration"`
740 When string `json:"when"`
741 Stages []stage `json:"stages"`
742 HTML string `json:"html"`
743 }
744 rows := make([]row, 0, len(v.PipeRows))
745 for _, pr := range v.PipeRows {
746 one := v
747 one.PipeRows = []PipeRow{pr}
748 item := row{
749 ID: pr.ID, Status: pr.Status, Label: pr.Label, Duration: pr.Duration, When: pr.When,
750 HTML: s.partial("pipe-rows", one),
751 }
752 for _, st := range pr.Stages {
753 jobs := make([]job, 0, len(st.Jobs))
754 for _, j := range st.Jobs {
755 jobs = append(jobs, job{ID: j.ID, Name: j.Name, Status: j.Status, Label: j.Label, Queue: j.Queue})
756 }
757 item.Stages = append(item.Stages, stage{Name: st.Name, Status: st.Status, Tip: st.Tip, Jobs: jobs})
758 }
759 rows = append(rows, item)
760 }
761 w.Header().Set("Content-Type", "application/json")
762 w.Header().Set("Cache-Control", "no-store")
763 _ = json.NewEncoder(w).Encode(map[string]any{"active": v.Live, "rows": rows})
764}
765
766func (s *Server) writePipeDetail(w http.ResponseWriter, v View) {
767 type job struct {
768 ID int64 `json:"id"`
769 Name string `json:"name"`
770 Status string `json:"status"`
771 Label string `json:"label"`
772 Stage string `json:"stage"`
773 Queue string `json:"queue"`
774 }
775 type stageJob struct {
776 ID int64 `json:"id"`
777 Name string `json:"name"`
778 Status string `json:"status"`
779 Label string `json:"label"`
780 Queue string `json:"queue"`
781 }
782 type stage struct {
783 Name string `json:"name"`
784 Status string `json:"status"`
785 Tip string `json:"tip"`
786 Jobs []stageJob `json:"jobs"`
787 }
788 jobs := make([]job, 0, len(v.PipeJobs))
789 for _, j := range v.PipeJobs {
790 jobs = append(jobs, job{ID: j.ID, Name: j.Name, Status: j.Status, Label: j.Label, Stage: j.Stage, Queue: j.Queue})
791 }
792 stages := make([]stage, 0, len(v.PipeStages))
793 for _, st := range v.PipeStages {
794 item := stage{Name: st.Name, Status: st.Status, Tip: st.Tip, Jobs: make([]stageJob, 0, len(st.Jobs))}
795 for _, j := range st.Jobs {
796 item.Jobs = append(item.Jobs, stageJob{ID: j.ID, Name: j.Name, Status: j.Status, Label: j.Label, Queue: j.Queue})
797 }
798 stages = append(stages, item)
799 }
800 dur := ""
801 html := ""
802 if v.Pipe != nil {
803 dur = pipelineClock(*v.Pipe)
804 if v.Repo != nil {
805 head := CommitRow{PipeID: v.Pipe.ID, PipeStages: v.PipeStages}
806 html = s.partial("stage-dots", View{Lang: v.Lang, Repo: v.Repo, Head: &head})
807 }
808 }
809 w.Header().Set("Content-Type", "application/json")
810 w.Header().Set("Cache-Control", "no-store")
811 _ = json.NewEncoder(w).Encode(map[string]any{
812 "active": v.Live, "status": v.PipeStatus, "label": v.PipeLabel,
813 "duration": dur, "jobs": jobs, "stages": stages, "html": html,
814 })
815}
816
817func clockOf(ts string) string {
818 if t, err := time.Parse(time.RFC3339, ts); err == nil {
819 return t.UTC().Format("15:04:05")
820 }
821 if len(ts) >= 19 && strings.Contains(ts, "T") {
822 return ts[11:19]
823 }
824 return ""
825}