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:
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.PushEvent:
214 switch l.view {
215 case "mr":
216 return l.mrPushed(ctx, ev)
217 case "mrs":
218 return nil, nil
219 }
220 switch l.view {
221 case "refs":
222 return l.refs(ctx, we.ID)
223 case "commits":
224 return l.banner(ctx, ev)
225 }
226 return l.lastPush(ctx)
227 }
228 return nil, nil
229}
230
231// lastPush is the "last push" fact of the summary.
232func (l *liveStream) lastPush(ctx context.Context) ([]fragment, error) {
233 view, err := l.repoByName(ctx, l.repo)
234 if err != nil {
235 return nil, err
236 }
237 f, err := renderFragment(ctx, "repo-last-push", FactValue(lastPushFact(view, l.s.cfg.Now())))
238 return []fragment{f}, err
239}
240
241// refs is the table of the refs page and the facts of its rail. The fragments
242// of one event are built once for all the watchers of the repository that
243// see the same things (see fanout); eventID names the event.
244func (l *liveStream) refs(ctx context.Context, eventID string) ([]fragment, error) {
245 key := fanKey{repo: l.repo, event: eventID, owner: SignedIn(ctx)}
246 return l.s.refsFan.do(ctx, key, func() ([]fragment, error) {
247 d, err := l.s.loadRepo(ctx, l.repo)
248 if err != nil {
249 return nil, err
250 }
251 p := l.s.refsPage(ctx, d)
252 body, err := renderFragment(ctx, "refs-list", RefsBody(p))
253 if err != nil {
254 return nil, err
255 }
256 kv, err := renderFragment(ctx, "refs-list", RefsKV(p))
257 return []fragment{body, kv}, err
258 })
259}
260
261const (
262 // fanTTL is how long the fragments of an event are kept for the watchers
263 // that are told of it a little later than the first.
264 fanTTL = 2 * time.Second
265 // fanMax bounds the events kept; past it an event is built for each
266 // watcher, as without sharing.
267 fanMax = 64
268)
269
270// fanKey says which watchers may share the fragments of an event: those of
271// the same repository, for the same event, and of the same class. The class
272// is anonymous or owner (a session is the owner's alone, ADR 0018): what is
273// built as the owner can show what an anonymous visitor may not see, so the
274// two never share an entry.
275type fanKey struct {
276 repo, event string
277 owner bool
278}
279
280type fanEntry struct {
281 done chan struct{} // closed once frags or err is set
282 frags []fragment
283 err error
284 at time.Time // when it was built; zero while it is
285}
286
287// fanout builds the fragments of an event once for the many watchers that
288// receive it: a push to a repository that 256 pages watch would otherwise
289// load the refs and the commits they designate 256 times. The zero value is
290// ready. A failure is never kept: the next watcher builds it again.
291type fanout struct {
292 mu sync.Mutex
293 m map[fanKey]*fanEntry
294}
295
296// do returns the fragments of key, built by build when nobody has or is
297// building them. build runs with the context of the watcher that calls it,
298// which is of the class of the key; a watcher whose builder failed (its
299// request was cancelled, say) does not fail the others, they build again.
300func (f *fanout) do(ctx context.Context, key fanKey, build func() ([]fragment, error)) ([]fragment, error) {
301 if key.event == "" {
302 return build() // no event to share by
303 }
304 for range 3 {
305 f.mu.Lock()
306 now := time.Now()
307 for k, e := range f.m {
308 if !e.at.IsZero() && now.Sub(e.at) > fanTTL {
309 delete(f.m, k)
310 }
311 }
312 e, shared := f.m[key]
313 if !shared {
314 if len(f.m) >= fanMax {
315 f.mu.Unlock()
316 return build()
317 }
318 if f.m == nil {
319 f.m = make(map[fanKey]*fanEntry)
320 }
321 e = &fanEntry{done: make(chan struct{})}
322 f.m[key] = e
323 }
324 f.mu.Unlock()
325
326 if !shared {
327 return f.lead(key, e, build)
328 }
329 select {
330 case <-e.done:
331 case <-ctx.Done():
332 return nil, ctx.Err()
333 }
334 if e.err == nil {
335 return e.frags, nil
336 }
337 }
338 return build()
339}
340
341// lead builds the entry that the caller registered.
342func (f *fanout) lead(key fanKey, e *fanEntry, build func() ([]fragment, error)) (frags []fragment, err error) {
343 err = errors.New("web: fragments were not built") // a panic of build
344 defer func() {
345 f.mu.Lock()
346 e.frags, e.err, e.at = frags, err, time.Now()
347 if err != nil && f.m[key] == e {
348 delete(f.m, key)
349 }
350 f.mu.Unlock()
351 close(e.done)
352 }()
353 return build()
354}
355
356// banner tells the commits page how many commits its branch got since the
357// head it lists.
358//
359//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
360func (l *liveStream) banner(ctx context.Context, p domain.PushEvent) ([]fragment, error) {
361 if l.ref == "" || !isFullID(l.head) {
362 return nil, nil
363 }
364 tip, touched := "", false
365 for _, u := range p.Updates {
366 if u.Ref == "refs/heads/"+l.ref {
367 tip, touched = u.New, true
368 if u.IsDelete() {
369 tip = ""
370 }
371 }
372 }
373 switch {
374 case !touched:
375 return nil, nil
376 case tip == "":
377 return gap, nil // the branch was deleted
378 }
379 text, err := l.bannerText(ctx, tip)
380 if err != nil {
381 return nil, err
382 }
383 c := LiveSlot("commits-head")
384 if text != "" {
385 c = CommitsBanner(text, repoHref(l.repo, "commits", l.ref))
386 }
387 f, err := renderFragment(ctx, "commits-head", c)
388 return []fragment{f}, err
389}
390
391func (l *liveStream) bannerText(ctx context.Context, tip string) (string, error) {
392 if tip == l.head {
393 return "", nil
394 }
395 if l.s.cfg.MergeRequests == nil {
396 // Without the merge request service there is no history summary: the
397 // banner only says the branch moved.
398 return "the branch moved — reload", nil
399 }
400 name, err := domain.ParseRepoName(l.repo)
401 if err != nil {
402 return "", err
403 }
404 oldHead, err := domain.ParseObjectID(l.head)
405 if err != nil {
406 return "", err
407 }
408 newTip, err := domain.ParseObjectID(tip)
409 if err != nil {
410 return "", err
411 }
412 res, err := l.s.cfg.MergeRequests.PushSummary(ctx, principal(ctx), name, oldHead, newTip)
413 if err != nil {
414 return "", err
415 }
416 return pushSummaryText(res), nil
417}
418
419func pushSummaryText(res ports.PushSummary) string {
420 switch {
421 case res.Rewritten:
422 return "the branch was rewritten — reload"
423 case res.More:
424 return newCommits(strconv.Itoa(res.Count)+"+", 2)
425 default:
426 return newCommits(strconv.Itoa(res.Count), res.Count)
427 }
428}
429
430// newCommits is the text of the banner: "1 new commit — reload".
431func newCommits(count string, n int) string {
432 if n == 1 {
433 return count + " new commit — reload"
434 }
435 return count + " new commits — reload"
436}
437
438// isFullID reports whether s is a full commit id.
439func isFullID(s string) bool { return len(s) == 40 && isCommitID(s) }
440
441// mrNotice tells a merge request page that something happened to the request
442// it shows, or the list that its content changed. Only a fixed sentence is sent:
443// the text of a comment or a title never leaves through the stream.
444func (l *liveStream) mrNotice(ctx context.Context, number int64, text string) ([]fragment, error) {
445 switch l.view {
446 case "mrs":
447 text = "merge requests changed — reload"
448 return l.notice(ctx, text, mrBase(l.repo))
449 case "mr":
450 if strconv.FormatInt(number, 10) != l.n {
451 return nil, nil
452 }
453 return l.notice(ctx, text, mrHref(l.repo, number))
454 }
455 return nil, nil
456}
457
458// issueNotice tells an issue page that something happened to the issue it
459// shows, or the list that its content changed. Like mrNotice it sends a fixed
460// sentence only, in the same slot.
461func (l *liveStream) issueNotice(ctx context.Context, number int64, text string) ([]fragment, error) {
462 switch l.view {
463 case "issues":
464 return l.notice(ctx, "issues changed — reload", issuesBase(l.repo))
465 case "issue":
466 if strconv.FormatInt(number, 10) != l.n {
467 return nil, nil
468 }
469 return l.notice(ctx, text, issueHref(l.repo, number))
470 }
471 return nil, nil
472}
473
474// mrPushed announces a push to the source branch of the merge request shown,
475// and has the badge follow a push to its source or its target.
476func (l *liveStream) mrPushed(ctx context.Context, p domain.PushEvent) ([]fragment, error) {
477 if _, err := strconv.ParseInt(l.n, 10, 64); err != nil {
478 return nil, nil
479 }
480 var out []fragment
481 moved := false
482 for _, u := range p.Updates {
483 switch {
484 case l.ref != "" && u.Ref == "refs/heads/"+l.ref:
485 out = append(out, fragment{event: "mr-head", html: `<div id="mr-head"></div>`})
486 moved = true
487 case l.target != "" && u.Ref == "refs/heads/"+l.target:
488 moved = true
489 }
490 if moved && len(out) > 0 {
491 break
492 }
493 }
494 if !moved {
495 return nil, nil
496 }
497 badge, err := l.mrMergeability(ctx)
498 return append(out, badge...), err
499}
500
501// mrMergeability is the badge of the merge box, read again: the result for the
502// tips as they are now, "checking" until the server has one (it then sends the
503// MergeRequestMergeability that turns the badge). Nothing for a request that
504// is not open.
505func (l *liveStream) mrMergeability(ctx context.Context) ([]fragment, error) {
506 if !SignedIn(ctx) || l.s.cfg.MergeRequests == nil {
507 return nil, nil // the box is the owner's
508 }
509 name, err := domain.ParseRepoName(l.repo)
510 if err != nil {
511 return nil, nil
512 }
513 n, err := strconv.ParseInt(l.n, 10, 64)
514 if err != nil {
515 return nil, nil
516 }
517 m, err := l.s.cfg.MergeRequests.Mergeability(ctx, principal(ctx), name, n)
518 switch {
519 case errors.Is(err, domain.ErrNotFound):
520 return gap, nil
521 case err != nil:
522 return nil, err
523 case m.State == "":
524 return nil, nil
525 }
526 f, err := renderFragment(ctx, "mr-mergeability", MRMergeabilityFragment(mergeabilityView(m, l.target)))
527 return []fragment{f}, err
528}
529
530func (l *liveStream) notice(ctx context.Context, text, href string) ([]fragment, error) {
531 f, err := renderFragment(ctx, "mr-notice", MRNotice(text, href))
532 return []fragment{f}, err
533}
534
535// runEvent updates the pages of CI that a RunUpdated changes: the row of the
536// list of runs, the recent actions of the summary, or the body of the run page
537// shown. Only a state is sent: the
538// events carry no log and no text of the workflow.
539func (l *liveStream) runEvent(ctx context.Context, ev domain.RunUpdated) ([]fragment, error) {
540 if l.s.cfg.Runs == nil {
541 return nil, nil
542 }
543 switch l.view {
544 case "actions":
545 f, err := renderFragment(ctx, "ci-run", RunListRow(l.s.runRow(l.repo, ev.Run, l.s.cfg.Now())))
546 if err != nil {
547 return nil, err
548 }
549 if ev.Run.Status == domain.CIQueued {
550 f.html = strings.Replace(f.html, "<tr id=", "<tr data-new id=", 1)
551 }
552 return []fragment{f}, nil
553 case "summary":
554 return l.recentActions(ctx)
555 case "run":
556 if strconv.FormatInt(ev.Run.ID, 10) != l.n {
557 return nil, nil
558 }
559 return l.runBody(ctx)
560 case "mr":
561 ofHead := ev.Run.CheckSha() == l.head
562 l.rememberRun(ev.Run.ID, ofHead)
563 if !ofHead {
564 return nil, nil
565 }
566 return l.mrChecks(ctx)
567 }
568 return nil, nil
569}
570
571// rememberRun records whether a run is one of the head of the page.
572func (l *liveStream) rememberRun(id int64, ofHead bool) {
573 if l.headRuns == nil || len(l.headRuns) >= maxHeadRuns {
574 l.headRuns = make(map[int64]bool)
575 }
576 l.headRuns[id] = ofHead
577}
578
579// jobOfHead tells whether the run of a job is one of the head of the page,
580// reading the run the first time.
581func (l *liveStream) jobOfHead(ctx context.Context, job domain.CIJob) (bool, error) {
582 if ofHead, known := l.headRuns[job.RunID]; known {
583 return ofHead, nil
584 }
585 run, err := l.s.cfg.Runs.GetRun(ctx, principal(ctx), job.Repo, job.RunID, 0)
586 switch {
587 case errors.Is(err, domain.ErrNotFound):
588 return false, nil
589 case err != nil:
590 return false, err
591 }
592 ofHead := run.Run.CheckSha() == l.head
593 l.rememberRun(job.RunID, ofHead)
594 return ofHead, nil
595}
596
597// mrChecks is the checks block of the merge request page, read again for the
598// head the page shows: a run or a job of that head changed. A job event does
599// not name its commit; reading the checks of the head is one store read, and
600// a job of another commit leaves them as they were.
601func (l *liveStream) mrChecks(ctx context.Context) ([]fragment, error) {
602 if !isFullID(l.head) {
603 return nil, nil
604 }
605 name, err := domain.ParseRepoName(l.repo)
606 if err != nil {
607 return nil, nil
608 }
609 repo, err := l.s.repoRecord(ctx, name)
610 switch {
611 case errors.Is(err, domain.ErrNotFound):
612 return gap, nil
613 case err != nil:
614 return nil, err
615 }
616 checks := l.s.checksFor(ctx, name, l.head)
617 f, err := renderFragment(ctx, "ci-run", MRChecks(checksSection(repo, checks)))
618 if err != nil {
619 return nil, err
620 }
621 sum, err := renderFragment(ctx, "ci-run", MRChecksSum(checksSummary(name, l.head, checks)))
622 return []fragment{f, sum}, err
623}
624
625// recentActions is the "Recent actions" block of the summary rail, read again
626// as the principal of the stream: the newest runs change with every event, and
627// a viewer who cannot read CI any more gets the block hidden and empty.
628func (l *liveStream) recentActions(ctx context.Context) ([]fragment, error) {
629 name, err := domain.ParseRepoName(l.repo)
630 if err != nil {
631 return nil, nil
632 }
633 a, err := l.s.listRecentActions(ctx, name, l.s.cfg.Now())
634 switch {
635 case errors.Is(err, domain.ErrNotFound):
636 a = RecentActions{AllHref: actionsBase(l.repo)}
637 case err != nil:
638 return nil, err
639 }
640 f, err := renderFragment(ctx, "ci-run", RecentActionsBlock(a))
641 return []fragment{f}, err
642}
643
644// jobEvent updates the body of the run page and the steps of the job page.
645func (l *liveStream) jobEvent(ctx context.Context, ev domain.JobUpdated) ([]fragment, error) {
646 if l.s.cfg.Runs == nil {
647 return nil, nil
648 }
649 switch l.view {
650 case "run":
651 if strconv.FormatInt(ev.Job.RunID, 10) != l.n {
652 return nil, nil
653 }
654 return l.runBody(ctx)
655 case "job":
656 if ev.Job.ID != l.job {
657 return nil, nil
658 }
659 return l.jobState(ctx)
660 case "mr":
661 if !isFullID(l.head) {
662 return nil, nil
663 }
664 ofHead, err := l.jobOfHead(ctx, ev.Job)
665 if err != nil || !ofHead {
666 return nil, err
667 }
668 return l.mrChecks(ctx)
669 }
670 return nil, nil
671}
672
673// runBody renders again the jobs of the run page.
674func (l *liveStream) runBody(ctx context.Context) ([]fragment, error) {
675 id, err := strconv.ParseInt(l.n, 10, 64)
676 if err != nil {
677 return nil, nil
678 }
679 d, err := l.s.loadRepo(ctx, l.repo)
680 if err != nil {
681 return nil, err
682 }
683 p, err := l.s.runPage(ctx, d, id, 0)
684 if err != nil {
685 return nil, err
686 }
687 body, err := renderFragment(ctx, "ci-run", runBodyFragment(p))
688 if err != nil {
689 return nil, err
690 }
691 // The buttons depend on the state: the page fetches itself again when the
692 // run completed, so that the owner gets the right ones.
693 if !p.Active {
694 return []fragment{body, {event: "gap", html: "gap"}}, nil
695 }
696 return []fragment{body}, nil
697}
698
699// jobState tells the job page that its state or its steps changed: the page
700// reloads the part of the log after the last line it holds (ermite.js).
701func (l *liveStream) jobState(ctx context.Context) ([]fragment, error) {
702 if l.sha == "" {
703 return gap, nil // the stream was set up without the commit of the run
704 }
705 d, err := l.s.loadRepo(ctx, l.repo)
706 if err != nil {
707 return nil, err
708 }
709 view, err := l.s.cfg.Runs.GetJob(ctx, principal(ctx), d.repo.Name, l.job, 0)
710 if err != nil {
711 return nil, err
712 }
713 now := l.s.cfg.Now()
714 row := l.s.jobRow(d.name(), view, now)
715 f, err := renderFragment(ctx, "ci-job", JobHead(row, view.Lines))
716 if err != nil {
717 return nil, err
718 }
719 steps, err := renderFragment(ctx, "ci-job", JobSteps(stepViews(view, now)))
720 if err != nil {
721 return nil, err
722 }
723 anns, more, err := l.s.jobAnnotations(ctx, d, view.RunID, l.sha, view, 0)
724 if err != nil {
725 return nil, err
726 }
727 notes, err := renderFragment(ctx, "ci-job", JobAnnotations(anns, more))
728 if err != nil {
729 return nil, err
730 }
731 return []fragment{f, steps, notes}, nil
732}