Skip to content
quarry Artifact [6c360e3fb4]
Login

Artifact [6c360e3fb4]

Artifact 6c360e3fb42ed685224b06beff6e780326039cdaeab2032ee111815ce51f3776:


package main

import (
	"sync"

	"craftdesign.group/quarry/internal/api"
	"craftdesign.group/quarry/internal/ci"
	"craftdesign.group/quarry/internal/oltp"
)

// unclaimedRuns is which unfinished runs no runner has taken up, as the
// poller last saw them, and since when. It is derived from the engine's
// own steps (ci.Run.Unclaimed) on every poll and never stored: a run
// reads "unclaimed" for as long as nothing has claimed it, and "running"
// the moment a step starts. After a restart the first poll refills it.
var unclaimedRuns = struct {
	mu    sync.Mutex
	since map[string]string
}{since: map[string]string{}}

// noteUnclaimed records what the engine says about one unfinished run.
// since is when the run was created; the row's start time stands in
// when the engine does not say.
func noteUnclaimed(runID string, run ci.Run, rowStarted string) {
	unclaimedRuns.mu.Lock()
	defer unclaimedRuns.mu.Unlock()
	if !run.Unclaimed() || startedBefore(run) {
		delete(unclaimedRuns.since, runID)
		return
	}
	since := run.CreatedAt
	if since == "" {
		since = rowStarted
	}
	unclaimedRuns.since[runID] = since
}

// unclaimedSince reports when a run began waiting for a runner, and
// whether it still is.
func unclaimedSince(runID string) (string, bool) {
	unclaimedRuns.mu.Lock()
	defer unclaimedRuns.mu.Unlock()
	s, ok := unclaimedRuns.since[runID]
	return s, ok
}

// markUnclaimed turns a not-yet-finished run into the status a reader
// should see when no runner has taken it up. A finished run is left
// alone whatever the table says.
func markUnclaimed(r oltp.CIRun, run *api.CIRun) {
	if ciTerminalStatus(r.Status) {
		return
	}
	if since, ok := unclaimedSince(r.RunID); ok {
		run.Status, run.WaitingSince = api.RunUnclaimed, since
	}
}

// startedBefore says some step of the run has started or finished: a
// run between two steps is waiting for its next dispatch, not for a
// runner, and must not read as unclaimed.
func startedBefore(run ci.Run) bool {
	for _, s := range run.Steps {
		if s.StartedAt != "" || s.CompletedAt != "" || s.Status == "completed" || s.Status == "failed" {
			return true
		}
	}
	return false
}

// forgetUnclaimedExcept drops every run the poller no longer holds as
// unfinished, so the table cannot outgrow the runs there are.
func forgetUnclaimedExcept(live map[string]bool) {
	unclaimedRuns.mu.Lock()
	defer unclaimedRuns.mu.Unlock()
	for id := range unclaimedRuns.since {
		if !live[id] {
			delete(unclaimedRuns.since, id)
		}
	}
}