1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package web
4
5import (
6 "bytes"
7 "context"
8 "errors"
9 "strconv"
10 "strings"
11 "sync"
12 "time"
13
14 "github.com/a-h/templ"
15
16 "bnema.dev/ermite/internal/domain"
17 "bnema.dev/ermite/internal/ports"
18)
19
20// liveStream turns the events of Watch into the fragments one page shows.
21type liveStream struct {
22 s *Server
23 repo string // "" on the home page
24 // filter is the repository the inbox is filtered on, "" for all.
25 filter string
26 view string // "summary", "refs" or "commits"
27 ref string // commits: the branch listed
28 head string // commits: the commit listed first
29 n string // mr: the number of the merge request shown; run: the run id
30 job string // job: the id of the job shown
31 target string // mr: the target branch of the merge request shown
32 // sha is the commit of the run of the job shown, read once when the stream
33 // is set up: the annotations link to files at it, and it never changes.
34 sha string
35 // headRuns says, on a merge request page, whether a run is one of the
36 // head shown (its checks are on that head); a job event does not carry
37 // its commit, so its run is read once. One stream reads it, no lock.
38 headRuns map[int64]bool
39}
40
41// maxHeadRuns bounds headRuns: past it the map starts again.
42const maxHeadRuns = 256
43
44// renderFragment renders a component to the data of an event.
45func renderFragment(ctx context.Context, event string, c templ.Component) (fragment, error) {
46 var b bytes.Buffer
47 if err := c.Render(ctx, &b); err != nil {
48 return fragment{}, err
49 }
50 return fragment{event: event, html: b.String()}, nil
51}
52
53var gap = []fragment{{event: "gap", html: "gap"}}
54
55// liveEvent reports whether the event of a watch is one the pages follow: a
56// gap, or one of the events of the forge. The use case may send others, which
57// no page shows and no stream carries, not even their id.
58func liveEvent(we ports.WatchEvent) bool {
59 if we.Gap {
60 return true
61 }
62 switch we.Event.(type) {
63 case domain.RepoCreated, domain.RepoUpdated, domain.RepoDeleted, domain.PushEvent,
64 domain.MergeRequestOpened, domain.MergeRequestMerged, domain.MergeRequestClosed, domain.MergeRequestReady, domain.MergeRequestMergeability, domain.CommentAdded, domain.CommentEdited, domain.CommentDeleted, domain.CommentResolved,
65 domain.RunUpdated, domain.JobUpdated,
66 domain.IssueOpened, domain.IssueClosed, domain.IssueReopened, domain.IssueCommented, domain.IssueSubmitted, domain.IssuePendingRemoved, domain.IssueReferenced:
67 return true
68 }
69 return false
70}
71
72// render returns the fragments for an event, none when it changes nothing on
73// the page.
74func (l *liveStream) render(ctx context.Context, we ports.WatchEvent) ([]fragment, error) {
75 if we.Gap {
76 return gap, nil
77 }
78 if we.Event == nil {
79 return nil, nil
80 }
81 if l.view == "inbox" {
82 return l.inbox(ctx, we)
83 }
84 if l.repo == "" {
85 return l.home(ctx, we)
86 }
87 return l.repoPage(ctx, we)
88}
89
90// repoByName reads a repository as the caller of the request. A name that is
91// not valid is a repository that is not there.
92func (l *liveStream) repoByName(ctx context.Context, rawName string) (ports.RepoView, error) {
93 name, err := domain.ParseRepoName(rawName)
94 if err != nil {
95 return ports.RepoView{}, domain.ErrNotFound
96 }
97 return l.s.repoView(ctx, name)
98}
99
100// home upserts the row of the repository an event is about. The row is read
101// again from the use case as the principal of the stream, so a repository
102// that was deleted or that the visitor can no longer see (public to private)
103// removes the row, and the stream never carries more than the list shows.
104func (l *liveStream) home(ctx context.Context, we ports.WatchEvent) ([]fragment, error) {
105 var name string
106 fresh := false
107 switch ev := we.Event.(type) {
108 case domain.RepoDeleted:
109 return l.gone(ctx, ev.Repo.String())
110 case domain.RepoCreated:
111 name = ev.Repo.String()
112 case domain.RepoUpdated:
113 name = ev.Repo.String()
114 case domain.PushEvent:
115 name, fresh = ev.Repo.String(), true
116 case domain.MergeRequestOpened:
117 name, fresh = ev.MergeRequest.Repo.String(), true
118 case domain.MergeRequestMerged:
119 name, fresh = ev.MergeRequest.Repo.String(), true
120 case domain.MergeRequestClosed:
121 name, fresh = ev.MergeRequest.Repo.String(), true
122 case domain.MergeRequestReady:
123 name, fresh = ev.MergeRequest.Repo.String(), true
124 case domain.CommentAdded:
125 name, fresh = ev.Repo.String(), true
126 case domain.IssueOpened:
127 name, fresh = ev.Issue.Repo.String(), true
128 case domain.IssueClosed:
129 name, fresh = ev.Issue.Repo.String(), true
130 case domain.IssueReopened:
131 name, fresh = ev.Issue.Repo.String(), true
132 case domain.IssueCommented:
133 name, fresh = ev.Repo.String(), true
134 case domain.RunUpdated:
135 name = ev.Run.Repo.String() // the CI state of the row
136 case domain.JobUpdated:
137 if ev.Job.Phase != domain.CIPhaseEnded {
138 return nil, nil
139 }
140 name = ev.Job.Repo.String() // a failed job turns the state to failing
141 default:
142 return nil, nil
143 }
144 view, err := l.repoByName(ctx, name)
145 switch {
146 case errors.Is(err, domain.ErrNotFound):
147 return l.gone(ctx, name)
148 case err != nil:
149 return nil, err
150 }
151 row := l.s.homeRowOf(ctx, view, l.s.cfg.Now(), false)
152 row.Fresh = fresh
153 f, err := renderFragment(ctx, "home-list", HomeRowView(row))
154 return []fragment{f}, err
155}
156
157func (l *liveStream) gone(ctx context.Context, name string) ([]fragment, error) {
158 f, err := renderFragment(ctx, "home-list", RepoGone("repo-"+name))
159 return []fragment{f}, err
160}
161
162// repoPage handles the events of the topic of one repository.
163func (l *liveStream) repoPage(ctx context.Context, we ports.WatchEvent) ([]fragment, error) {
164 switch ev := we.Event.(type) {
165 case domain.RunUpdated:
166 return l.runEvent(ctx, ev)
167 case domain.JobUpdated:
168 return l.jobEvent(ctx, ev)
169 case domain.RepoDeleted, domain.RepoCreated:
170 // Gone, or a new repository under the same name: whatever the page
171 // shows is not true any more.
172 return gap, nil
173 case domain.RepoUpdated:
174 _, err := l.repoByName(ctx, l.repo)
175 switch {
176 case errors.Is(err, domain.ErrNotFound):
177 return gap, nil // no longer visible
178 case err != nil:
179 return nil, err
180 case l.view == "summary", l.view == "refs":
181 return gap, nil // the description, the default branch
182 }
183 return nil, nil
184 case domain.MergeRequestOpened:
185 return l.mrNotice(ctx, ev.MergeRequest.Number, "a merge request was opened — reload")
186 case domain.MergeRequestMerged:
187 return l.mrNotice(ctx, ev.MergeRequest.Number, "this merge request was merged — reload")
188 case domain.MergeRequestClosed:
189 return l.mrNotice(ctx, ev.MergeRequest.Number, "this merge request was closed — reload")
190 case domain.MergeRequestReady:
191 return l.mrNotice(ctx, ev.MergeRequest.Number, "this merge request is ready for review — reload")
192 case domain.MergeRequestMergeability:
193 if l.view != "mr" || strconv.FormatInt(ev.Number, 10) != l.n {
194 return nil, nil
195 }
196 return l.mrMergeability(ctx)
197 case domain.CommentEdited:
198 return l.mrNotice(ctx, ev.Number, "a note was edited — reload")
199 case domain.CommentDeleted:
200 return l.mrNotice(ctx, ev.Number, "a note was deleted — reload")
201 case domain.CommentResolved:
202 return l.mrNotice(ctx, ev.Number, "a thread was resolved — reload")
203 case domain.CommentAdded:
204 return l.mrNotice(ctx, ev.Number, "a comment was added — reload")
205 case domain.IssueOpened:
206 return l.issueNotice(ctx, ev.Issue.Number, "an issue was opened — reload")
207 case domain.IssueClosed:
208 return l.issueNotice(ctx, ev.Issue.Number, "this issue was closed — reload")
209 case domain.IssueReopened:
210 return l.issueNotice(ctx, ev.Issue.Number, "this issue was reopened — reload")
211 case domain.IssueCommented:
212 return l.issueNotice(ctx, ev.Number, "a comment was added — reload")
213 case domain.IssueReferenced:
214 return l.issueNotice(ctx, ev.Issue, "a merge request mentions this issue — reload")
215 case domain.PushEvent:
216 switch l.view {
217 case "mr":
218 return l.mrPushed(ctx, ev)
219 case "mrs":
220 return nil, nil
221 }
222 switch l.view {
223 case "refs":
224 return l.refs(ctx, we.ID)
225 case "commits":
226 return l.banner(ctx, ev)
227 }
228 return l.lastPush(ctx)
229 }
230 return nil, nil
231}
232
233// lastPush is the "last push" fact of the summary.
234func (l *liveStream) lastPush(ctx context.Context) ([]fragment, error) {
235 view, err := l.repoByName(ctx, l.repo)
236 if err != nil {
237 return nil, err
238 }
239 f, err := renderFragment(ctx, "repo-last-push", FactValue(lastPushFact(view, l.s.cfg.Now())))
240 return []fragment{f}, err
241}
242
243// refs is the table of the refs page and the facts of its rail. The fragments
244// of one event are built once for all the watchers of the repository that
245// see the same things (see fanout); eventID names the event.
246func (l *liveStream) refs(ctx context.Context, eventID string) ([]fragment, error) {
247 key := fanKey{repo: l.repo, event: eventID, owner: SignedIn(ctx)}
248 return l.s.refsFan.do(ctx, key, func() ([]fragment, error) {
249 d, err := l.s.loadRepo(ctx, l.repo)
250 if err != nil {
251 return nil, err
252 }
253 p := l.s.refsPage(ctx, d)
254 body, err := renderFragment(ctx, "refs-list", RefsBody(p))
255 if err != nil {
256 return nil, err
257 }
258 kv, err := renderFragment(ctx, "refs-list", RefsKV(p))
259 return []fragment{body, kv}, err
260 })
261}
262
263const (
264 // fanTTL is how long the fragments of an event are kept for the watchers
265 // that are told of it a little later than the first.
266 fanTTL = 2 * time.Second
267 // fanMax bounds the events kept; past it an event is built for each
268 // watcher, as without sharing.
269 fanMax = 64
270)
271
272// fanKey says which watchers may share the fragments of an event: those of
273// the same repository, for the same event, and of the same class. The class
274// is anonymous or owner (a session is the owner's alone, ADR 0018): what is
275// built as the owner can show what an anonymous visitor may not see, so the
276// two never share an entry.
277type fanKey struct {
278 repo, event string
279 owner bool
280}
281
282type fanEntry struct {
283 done chan struct{} // closed once frags or err is set
284 frags []fragment
285 err error
286 at time.Time // when it was built; zero while it is
287}
288
289// fanout builds the fragments of an event once for the many watchers that
290// receive it: a push to a repository that 256 pages watch would otherwise
291// load the refs and the commits they designate 256 times. The zero value is
292// ready. A failure is never kept: the next watcher builds it again.
293type fanout struct {
294 mu sync.Mutex
295 m map[fanKey]*fanEntry
296}
297
298// do returns the fragments of key, built by build when nobody has or is
299// building them. build runs with the context of the watcher that calls it,
300// which is of the class of the key; a watcher whose builder failed (its
301// request was cancelled, say) does not fail the others, they build again.
302func (f *fanout) do(ctx context.Context, key fanKey, build func() ([]fragment, error)) ([]fragment, error) {
303 if key.event == "" {
304 return build() // no event to share by
305 }
306 for range 3 {
307 f.mu.Lock()
308 now := time.Now()
309 for k, e := range f.m {
310 if !e.at.IsZero() && now.Sub(e.at) > fanTTL {
311 delete(f.m, k)
312 }
313 }
314 e, shared := f.m[key]
315 if !shared {
316 if len(f.m) >= fanMax {
317 f.mu.Unlock()
318 return build()
319 }
320 if f.m == nil {
321 f.m = make(map[fanKey]*fanEntry)
322 }
323 e = &fanEntry{done: make(chan struct{})}
324 f.m[key] = e
325 }
326 f.mu.Unlock()
327
328 if !shared {
329 return f.lead(key, e, build)
330 }
331 select {
332 case <-e.done:
333 case <-ctx.Done():
334 return nil, ctx.Err()
335 }
336 if e.err == nil {
337 return e.frags, nil
338 }
339 }
340 return build()
341}
342
343// lead builds the entry that the caller registered.
344func (f *fanout) lead(key fanKey, e *fanEntry, build func() ([]fragment, error)) (frags []fragment, err error) {
345 err = errors.New("web: fragments were not built") // a panic of build
346 defer func() {
347 f.mu.Lock()
348 e.frags, e.err, e.at = frags, err, time.Now()
349 if err != nil && f.m[key] == e {
350 delete(f.m, key)
351 }
352 f.mu.Unlock()
353 close(e.done)
354 }()
355 return build()
356}
357
358// banner tells the commits page how many commits its branch got since the
359// head it lists.
360//
361//hexcheck:ignore suspicious-business-logic-in-adapter picks the update of the listed branch from the push event; the count and rewrite come from MergeRequests.PushSummary
362func (l *liveStream) banner(ctx context.Context, p domain.PushEvent) ([]fragment, error) {
363 if l.ref == "" || !isFullID(l.head) {
364 return nil, nil
365 }
366 tip, touched := "", false
367 for _, u := range p.Updates {
368 if u.Ref == "refs/heads/"+l.ref {
369 tip, touched = u.New, true
370 if u.IsDelete() {
371 tip = ""
372 }
373 }
374 }
375 switch {
376 case !touched:
377 return nil, nil
378 case tip == "":
379 return gap, nil // the branch was deleted
380 }
381 text, err := l.bannerText(ctx, tip)
382 if err != nil {
383 return nil, err
384 }
385 c := LiveSlot("commits-head")
386 if text != "" {
387 c = CommitsBanner(text, repoHref(l.repo, "commits", l.ref))
388 }
389 f, err := renderFragment(ctx, "commits-head", c)
390 return []fragment{f}, err
391}
392
393func (l *liveStream) bannerText(ctx context.Context, tip string) (string, error) {
394 if tip == l.head {
395 return "", nil
396 }
397 if l.s.cfg.MergeRequests == nil {
398 // Without the merge request service there is no history summary: the
399 // banner only says the branch moved.
400 return "the branch moved — reload", nil
401 }
402 name, err := domain.ParseRepoName(l.repo)
403 if err != nil {
404 return "", err
405 }
406 oldHead, err := domain.ParseObjectID(l.head)
407 if err != nil {
408 return "", err
409 }
410 newTip, err := domain.ParseObjectID(tip)
411 if err != nil {
412 return "", err
413 }
414 res, err := l.s.cfg.MergeRequests.PushSummary(ctx, principal(ctx), name, oldHead, newTip)
415 if err != nil {
416 return "", err
417 }
418 return pushSummaryText(res), nil
419}
420
421func pushSummaryText(res ports.PushSummary) string {
422 switch {
423 case res.Rewritten:
424 return "the branch was rewritten — reload"
425 case res.More:
426 return newCommits(strconv.Itoa(res.Count)+"+", 2)
427 default:
428 return newCommits(strconv.Itoa(res.Count), res.Count)
429 }
430}
431
432// newCommits is the text of the banner: "1 new commit — reload".
433func newCommits(count string, n int) string {
434 if n == 1 {
435 return count + " new commit — reload"
436 }
437 return count + " new commits — reload"
438}
439
440// isFullID reports whether s is a full commit id.
441func isFullID(s string) bool { return len(s) == 40 && isCommitID(s) }
442
443// mrNotice tells a merge request page that something happened to the request
444// it shows, or the list that its content changed. Only a fixed sentence is sent:
445// the text of a comment or a title never leaves through the stream.
446func (l *liveStream) mrNotice(ctx context.Context, number int64, text string) ([]fragment, error) {
447 switch l.view {
448 case "mrs":
449 text = "merge requests changed — reload"
450 return l.notice(ctx, text, mrBase(l.repo))
451 case "mr":
452 if strconv.FormatInt(number, 10) != l.n {
453 return nil, nil
454 }
455 return l.notice(ctx, text, mrHref(l.repo, number))
456 }
457 return nil, nil
458}
459
460// issueNotice tells an issue page that something happened to the issue it
461// shows, or the list that its content changed. Like mrNotice it sends a fixed
462// sentence only, in the same slot.
463func (l *liveStream) issueNotice(ctx context.Context, number int64, text string) ([]fragment, error) {
464 switch l.view {
465 case "issues":
466 return l.notice(ctx, "issues changed — reload", issuesBase(l.repo))
467 case "issue":
468 if strconv.FormatInt(number, 10) != l.n {
469 return nil, nil
470 }
471 return l.notice(ctx, text, issueHref(l.repo, number))
472 }
473 return nil, nil
474}
475
476// mrPushed announces a push to the source branch of the merge request shown,
477// and has the badge follow a push to its source or its target.
478func (l *liveStream) mrPushed(ctx context.Context, p domain.PushEvent) ([]fragment, error) {
479 if _, err := strconv.ParseInt(l.n, 10, 64); err != nil {
480 return nil, nil
481 }
482 var out []fragment
483 moved := false
484 for _, u := range p.Updates {
485 switch {
486 case l.ref != "" && u.Ref == "refs/heads/"+l.ref:
487 out = append(out, fragment{event: "mr-head", html: `<div id="mr-head"></div>`})
488 moved = true
489 case l.target != "" && u.Ref == "refs/heads/"+l.target:
490 moved = true
491 }
492 if moved && len(out) > 0 {
493 break
494 }
495 }
496 if !moved {
497 return nil, nil
498 }
499 badge, err := l.mrMergeability(ctx)
500 return append(out, badge...), err
501}
502
503// mrMergeability is the badge of the merge box, read again: the result for the
504// tips as they are now, "checking" until the server has one (it then sends the
505// MergeRequestMergeability that turns the badge). Nothing for a request that
506// is not open.
507func (l *liveStream) mrMergeability(ctx context.Context) ([]fragment, error) {
508 if !SignedIn(ctx) || l.s.cfg.MergeRequests == nil {
509 return nil, nil // the box is the owner's
510 }
511 name, err := domain.ParseRepoName(l.repo)
512 if err != nil {
513 return nil, nil
514 }
515 n, err := strconv.ParseInt(l.n, 10, 64)
516 if err != nil {
517 return nil, nil
518 }
519 m, err := l.s.cfg.MergeRequests.Mergeability(ctx, principal(ctx), name, n)
520 switch {
521 case errors.Is(err, domain.ErrNotFound):
522 return gap, nil
523 case err != nil:
524 return nil, err
525 case m.State == "":
526 return nil, nil
527 }
528 f, err := renderFragment(ctx, "mr-mergeability", MRMergeabilityFragment(mergeabilityView(m, l.target)))
529 return []fragment{f}, err
530}
531
532func (l *liveStream) notice(ctx context.Context, text, href string) ([]fragment, error) {
533 f, err := renderFragment(ctx, "mr-notice", MRNotice(text, href))
534 return []fragment{f}, err
535}
536
537// runEvent updates the pages of CI that a RunUpdated changes: the row of the
538// list of runs, the recent actions of the summary, or the body of the run page
539// shown. Only a state is sent: the
540// events carry no log and no text of the workflow.
541func (l *liveStream) runEvent(ctx context.Context, ev domain.RunUpdated) ([]fragment, error) {
542 if l.s.cfg.Runs == nil {
543 return nil, nil
544 }
545 switch l.view {
546 case "actions":
547 f, err := renderFragment(ctx, "ci-run", RunListRow(l.s.runRow(l.repo, ev.Run, l.s.cfg.Now())))
548 if err != nil {
549 return nil, err
550 }
551 if ev.Run.Status == domain.CIQueued {
552 f.html = strings.Replace(f.html, "<tr id=", "<tr data-new id=", 1)
553 }
554 return []fragment{f}, nil
555 case "summary":
556 return l.recentActions(ctx)
557 case "run":
558 if strconv.FormatInt(ev.Run.ID, 10) != l.n {
559 return nil, nil
560 }
561 return l.runBody(ctx)
562 case "mr":
563 ofHead := ev.Run.CheckSha() == l.head
564 l.rememberRun(ev.Run.ID, ofHead)
565 if !ofHead {
566 return nil, nil
567 }
568 return l.mrChecks(ctx)
569 }
570 return nil, nil
571}
572
573// rememberRun records whether a run is one of the head of the page.
574func (l *liveStream) rememberRun(id int64, ofHead bool) {
575 if l.headRuns == nil || len(l.headRuns) >= maxHeadRuns {
576 l.headRuns = make(map[int64]bool)
577 }
578 l.headRuns[id] = ofHead
579}
580
581// jobOfHead tells whether the run of a job is one of the head of the page,
582// reading the run the first time.
583func (l *liveStream) jobOfHead(ctx context.Context, job domain.CIJob) (bool, error) {
584 if ofHead, known := l.headRuns[job.RunID]; known {
585 return ofHead, nil
586 }
587 run, err := l.s.cfg.Runs.GetRun(ctx, principal(ctx), job.Repo, job.RunID, 0)
588 switch {
589 case errors.Is(err, domain.ErrNotFound):
590 return false, nil
591 case err != nil:
592 return false, err
593 }
594 ofHead := run.Run.CheckSha() == l.head
595 l.rememberRun(job.RunID, ofHead)
596 return ofHead, nil
597}
598
599// mrChecks is the checks block of the merge request page, read again for the
600// head the page shows: a run or a job of that head changed. A job event does
601// not name its commit; reading the checks of the head is one store read, and
602// a job of another commit leaves them as they were.
603func (l *liveStream) mrChecks(ctx context.Context) ([]fragment, error) {
604 if !isFullID(l.head) {
605 return nil, nil
606 }
607 name, err := domain.ParseRepoName(l.repo)
608 if err != nil {
609 return nil, nil
610 }
611 repo, err := l.s.repoRecord(ctx, name)
612 switch {
613 case errors.Is(err, domain.ErrNotFound):
614 return gap, nil
615 case err != nil:
616 return nil, err
617 }
618 checks := l.s.checksFor(ctx, name, l.head)
619 f, err := renderFragment(ctx, "ci-run", MRChecks(checksSection(repo, checks)))
620 if err != nil {
621 return nil, err
622 }
623 sum, err := renderFragment(ctx, "ci-run", MRChecksSum(checksSummary(name, l.head, checks)))
624 return []fragment{f, sum}, err
625}
626
627// recentActions is the "Recent actions" block of the summary rail, read again
628// as the principal of the stream: the newest runs change with every event, and
629// a viewer who cannot read CI any more gets the block hidden and empty.
630func (l *liveStream) recentActions(ctx context.Context) ([]fragment, error) {
631 name, err := domain.ParseRepoName(l.repo)
632 if err != nil {
633 return nil, nil
634 }
635 a, err := l.s.listRecentActions(ctx, name, l.s.cfg.Now())
636 switch {
637 case errors.Is(err, domain.ErrNotFound):
638 a = RecentActions{AllHref: actionsBase(l.repo)}
639 case err != nil:
640 return nil, err
641 }
642 f, err := renderFragment(ctx, "ci-run", RecentActionsBlock(a))
643 return []fragment{f}, err
644}
645
646// jobEvent updates the body of the run page and the steps of the job page.
647func (l *liveStream) jobEvent(ctx context.Context, ev domain.JobUpdated) ([]fragment, error) {
648 if l.s.cfg.Runs == nil {
649 return nil, nil
650 }
651 switch l.view {
652 case "run":
653 if strconv.FormatInt(ev.Job.RunID, 10) != l.n {
654 return nil, nil
655 }
656 return l.runBody(ctx)
657 case "job":
658 if ev.Job.ID != l.job {
659 return nil, nil
660 }
661 return l.jobState(ctx)
662 case "mr":
663 if !isFullID(l.head) {
664 return nil, nil
665 }
666 ofHead, err := l.jobOfHead(ctx, ev.Job)
667 if err != nil || !ofHead {
668 return nil, err
669 }
670 return l.mrChecks(ctx)
671 }
672 return nil, nil
673}
674
675// runBody renders again the jobs of the run page.
676func (l *liveStream) runBody(ctx context.Context) ([]fragment, error) {
677 id, err := strconv.ParseInt(l.n, 10, 64)
678 if err != nil {
679 return nil, nil
680 }
681 d, err := l.s.loadRepo(ctx, l.repo)
682 if err != nil {
683 return nil, err
684 }
685 p, err := l.s.runPage(ctx, d, id, 0)
686 if err != nil {
687 return nil, err
688 }
689 body, err := renderFragment(ctx, "ci-run", runBodyFragment(p))
690 if err != nil {
691 return nil, err
692 }
693 // The buttons depend on the state: the page fetches itself again when the
694 // run completed, so that the owner gets the right ones.
695 if !p.Active {
696 return []fragment{body, {event: "gap", html: "gap"}}, nil
697 }
698 return []fragment{body}, nil
699}
700
701// jobState tells the job page that its state or its steps changed: the page
702// reloads the part of the log after the last line it holds (ermite.js).
703func (l *liveStream) jobState(ctx context.Context) ([]fragment, error) {
704 if l.sha == "" {
705 return gap, nil // the stream was set up without the commit of the run
706 }
707 d, err := l.s.loadRepo(ctx, l.repo)
708 if err != nil {
709 return nil, err
710 }
711 view, err := l.s.cfg.Runs.GetJob(ctx, principal(ctx), d.repo.Name, l.job, 0)
712 if err != nil {
713 return nil, err
714 }
715 now := l.s.cfg.Now()
716 row := l.s.jobRow(d.name(), view, now)
717 f, err := renderFragment(ctx, "ci-job", JobHead(row, view.Lines))
718 if err != nil {
719 return nil, err
720 }
721 steps, err := renderFragment(ctx, "ci-job", JobSteps(stepViews(view, now)))
722 if err != nil {
723 return nil, err
724 }
725 anns, more, err := l.s.jobAnnotations(ctx, d, view.RunID, l.sha, view, 0)
726 if err != nil {
727 return nil, err
728 }
729 notes, err := renderFragment(ctx, "ci-job", JobAnnotations(anns, more))
730 if err != nil {
731 return nil, err
732 }
733 return []fragment{f, steps, notes}, nil
734}