summaryrefslogtreecommitdiff
path: root/internal/api/task_view.go
blob: 6a4b58ee87b895ad570725db9919a0109f229e0c (plain)
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
package api

import (
	"database/sql"

	"github.com/thepeterstone/claudomator/internal/deployment"
	"github.com/thepeterstone/claudomator/internal/task"
)

// taskView wraps a task with computed fields that are derived from execution
// history and deployment state. It is used as the JSON response type for task
// list and get endpoints so that callers receive enriched data in one request.
type taskView struct {
	*task.Task
	Changestats      *task.Changestats  `json:"changestats,omitempty"`
	DeploymentStatus *deployment.Status `json:"deployment_status,omitempty"`
	ErrorMsg         string             `json:"error_msg,omitempty"`
}

var failedStates = map[task.State]bool{
	task.StateFailed:        true,
	task.StateBudgetExceeded: true,
	task.StateTimedOut:      true,
}

// enrichTask fetches the latest execution for the given task and attaches
// changestats, deployment_status, and error_msg fields.
func (s *Server) enrichTask(tk *task.Task) *taskView {
	view := &taskView{Task: tk}

	exec, err := s.store.GetLatestExecution(tk.ID)
	if err != nil {
		if err == sql.ErrNoRows && tk.State == task.StateReady {
			view.DeploymentStatus = deployment.Check(nil, tk.RepositoryURL)
		}
		return view
	}

	if failedStates[tk.State] && exec.ErrorMsg != "" {
		view.ErrorMsg = exec.ErrorMsg
	}
	if tk.State == task.StateReady {
		view.Changestats = exec.Changestats
		view.DeploymentStatus = deployment.Check(exec.Commits, tk.RepositoryURL)
	}
	return view
}