diff --git a/.agents/skills/add-go-docstrings/SKILL.md b/.agents/skills/add-go-docstrings/SKILL.md new file mode 100644 index 00000000..2f987aff --- /dev/null +++ b/.agents/skills/add-go-docstrings/SKILL.md @@ -0,0 +1,21 @@ +--- +name: add-go-docstrings +description: Add Go doc comments to exported Go symbols. Use when creating or updating exported types, functions, methods, or constant blocks in the AutoBuild executor Go module that lack doc comments. +metadata: + version: "1.0" + language: go +--- + +# Add Go Doc Comments + +Prepend a Go-style doc comment (`// SymbolName ...`) directly above any exported Go symbol (type, function, method, or constant block) that lacks one. + +## Rules +- **Format:** Start the comment with the exact symbol name (`// SymbolName ...`). +- **Length:** Keep it to one or two sentences covering what the symbol does, plus any notable preconditions or return values. +- **Scope:** Apply to all `.go` files under the AutoBuild executor module. + +## Do Not Comment +- Unexported symbols, unless the logic is non-obvious. +- Struct fields (document them in the type-level doc comment instead). +- Generated files. diff --git a/.claude/skills b/.claude/skills new file mode 120000 index 00000000..2b7a412b --- /dev/null +++ b/.claude/skills @@ -0,0 +1 @@ +../.agents/skills \ No newline at end of file diff --git a/apis/opencollection/pipelinecollection/.gitignore b/apis/opencollection/pipelinecollection/.gitignore new file mode 100644 index 00000000..ecf22714 --- /dev/null +++ b/apis/opencollection/pipelinecollection/.gitignore @@ -0,0 +1 @@ +TestRequests/* diff --git a/executor/.env.local b/executor/.env.local new file mode 100644 index 00000000..60821287 --- /dev/null +++ b/executor/.env.local @@ -0,0 +1,3 @@ +EXECUTOR_PORT=8080 + +EXECUTOR_DB_DSN="autobuild.db" diff --git a/executor/.gitignore b/executor/.gitignore new file mode 100644 index 00000000..d9e81f03 --- /dev/null +++ b/executor/.gitignore @@ -0,0 +1 @@ +autobuild.db diff --git a/executor/README.md b/executor/README.md new file mode 100644 index 00000000..ac9dafef --- /dev/null +++ b/executor/README.md @@ -0,0 +1,29 @@ +# Executor Go Module + +## Prod like execution +Script to startup dagger + +```sh +docker run \ + --name dagger-engine \ + --privileged \ + -p 8081:8081 \ + -e DAGGER_ENGINE_PORT=8081 \ + -v dagger-engine-cache:/var/lib/dagger \ + --restart unless-stopped \ + registry.dagger.io/engine:v0.21.11 +``` + +Script to start go service + +```sh +_EXPERIMENTAL_DAGGER_RUNNER_HOST=tcp://localhost:8081 EXECUTOR_PROFILE=local go run main.go +``` + +## Local Execution + +```sh +EXECUTOR_PROFILE=local go run main.go +``` + +No separate dagger service is required as it will fallback to starting it's own container. diff --git a/executor/config/appEnv.go b/executor/config/appEnv.go new file mode 100644 index 00000000..05987571 --- /dev/null +++ b/executor/config/appEnv.go @@ -0,0 +1,28 @@ +package config + +import ( + "log" + "os" + "slices" + + "github.com/joho/godotenv" +) + +var validProfiles = [1]string{"local"} + +// LoadProfile loads the environment variables for the given application profile. +// The profile is read from the EXECUTOR_PROFILE environment variable. +// Valid profiles are defined in validProfiles. The corresponding .env. file is loaded via godotenv. +func LoadProfile() { + appProfile := os.Getenv("EXECUTOR_PROFILE") + + if appProfile == "" || !slices.Contains(validProfiles[:], appProfile) { + log.Fatal("Please pass along a valid application profile") + } + + envFile := ".env." + appProfile + err := godotenv.Load(envFile) + if err != nil { + log.Fatal("Error ocurred while loading env file: ", envFile) + } +} diff --git a/executor/config/server.go b/executor/config/server.go new file mode 100644 index 00000000..2abeaf51 --- /dev/null +++ b/executor/config/server.go @@ -0,0 +1,25 @@ +package config + +import ( + "net/http" + "os" + "time" +) + +// InitServer creates and returns an HTTP server bound to localhost on the port +// specified by the EXECUTOR_PORT environment variable. +func InitServer(mux *http.ServeMux) (string, *http.Server) { + // Configure server settings explicitly + serverAddr := "127.0.0.1:" + os.Getenv("EXECUTOR_PORT") + // 10s: GitHub webhook spec requires a 2XX response within 10s or the delivery is marked failed + const maxOpsTime = 10 * time.Second + + server := &http.Server{ + Addr: serverAddr, + Handler: mux, + ReadTimeout: maxOpsTime, + WriteTimeout: maxOpsTime, + MaxHeaderBytes: 1 << 20, // 1 MB: matches Go's http.DefaultMaxHeaderBytes + } + return serverAddr, server +} diff --git a/executor/dto/dto.go b/executor/dto/dto.go new file mode 100644 index 00000000..14a1eb48 --- /dev/null +++ b/executor/dto/dto.go @@ -0,0 +1,51 @@ +package dto + +import "github.com/google/uuid" + +// StageBuildDTO represents the execution state of a single stage within a pipeline build. +type StageBuildDTO struct { + Id uuid.UUID `json:"id"` + + StageId uuid.UUID `json:"stageId"` + + StageName string `json:"stageName"` + + StageOrder int `json:"stageOrder"` + + CurrentState StageExecutionState `json:"stageExecutionState"` +} + +// PipelineBuildDTO represents the execution state of a full pipeline run, including all its stage builds. +type PipelineBuildDTO struct { + Id uuid.UUID `json:"id"` + + PipelineId uuid.UUID `json:"pipelineId"` + + PipelineName string `json:"pipelineName"` + + CurrentState PipelineExecutionState `json:"currentState"` + + StageBuilds []StageBuildDTO `json:"stageBuilds"` +} + +// StageDTO carries the definition of a single pipeline stage as received from the caller. +type StageDTO struct { + Id uuid.UUID `json:"id"` + + Name string `json:"name"` + + ScriptType string `json:"scriptType"` + + Command string `json:"command"` + + StageOrder int `json:"stageOrder"` +} + +// PipelineDTO carries the definition of a pipeline and its ordered stages as received from the caller. +type PipelineDTO struct { + Id uuid.UUID `json:"id"` + + Name string `json:"name"` + + Stages []StageDTO `json:"stages"` +} diff --git a/executor/dto/state.go b/executor/dto/state.go new file mode 100644 index 00000000..95847252 --- /dev/null +++ b/executor/dto/state.go @@ -0,0 +1,24 @@ +package dto + +// StageExecutionState represents the lifecycle state of an individual stage build. +type StageExecutionState string + +const ( + StageWaiting StageExecutionState = "WAITING" + StageRunning StageExecutionState = "RUNNING" + StageSuccess StageExecutionState = "SUCCESS" + StageFailed StageExecutionState = "FAILED" + StageStopped StageExecutionState = "STOPPED" +) + + +// PipelineExecutionState represents the lifecycle state of a pipeline build. + type PipelineExecutionState string + + const ( + PipelineWaiting PipelineExecutionState = "WAITING" + PipelineRunning PipelineExecutionState = "RUNNING" + PipelineSuccess PipelineExecutionState = "SUCCESS" + PipelineFailed PipelineExecutionState = "FAILED" + ) + diff --git a/executor/entity/entity.go b/executor/entity/entity.go new file mode 100644 index 00000000..70979d3e --- /dev/null +++ b/executor/entity/entity.go @@ -0,0 +1,72 @@ +package entity + +import ( + "github.com/google/uuid" + "gorm.io/gorm" +) + +// PipelineExecutionState represents the lifecycle state of a pipeline build record. +type PipelineExecutionState string + +const ( + PipelineWaiting PipelineExecutionState = "WAITING" + PipelineRunning PipelineExecutionState = "RUNNING" + PipelineSuccess PipelineExecutionState = "SUCCESS" + PipelineFailed PipelineExecutionState = "FAILED" +) + +// StageExecutionState represents the lifecycle state of an individual stage build record. +type StageExecutionState string + +const ( + StageWaiting StageExecutionState = "WAITING" + StageRunning StageExecutionState = "RUNNING" + StageSuccess StageExecutionState = "SUCCESS" + StageFailed StageExecutionState = "FAILED" + StageStopped StageExecutionState = "STOPPED" +) + +// StageBuild is the GORM entity that persists the execution record of a single pipeline stage. +type StageBuild struct { + ID uuid.UUID `gorm:"type:uuid;primaryKey"` + StageID uuid.UUID `gorm:"type:uuid;not null;column:stage_id"` + StageName string `gorm:"type:varchar(255);not null;column:stage_name"` + CurrentState StageExecutionState `gorm:"type:varchar(20);not null;column:stage_build_current_state;default:WAITING"` + StageOrder int `gorm:"not null;column:stage_order"` + LogPath string `gorm:"not null;column:log_path"` +} + +func (s *StageBuild) BeforeCreate(tx *gorm.DB) error { + if s.ID == uuid.Nil { + s.ID = uuid.New() + } + if s.CurrentState == "" { + s.CurrentState = StageWaiting + } + return nil +} + +// PipelineStageBuild is the join-table entity that links a PipelineBuild to its StageBuild records. +type PipelineStageBuild struct { + PipelineBuildID uuid.UUID `gorm:"type:uuid;primaryKey;column:pipeline_build_id;constraint:OnDelete:CASCADE;"` + StageBuildID uuid.UUID `gorm:"type:uuid;primaryKey;column:stage_build_id;constraint:OnDelete:CASCADE;"` +} + +// PipelineBuild is the GORM entity that persists the execution record of a full pipeline run. +type PipelineBuild struct { + ID uuid.UUID `gorm:"type:uuid;primaryKey"` + PipelineID uuid.UUID `gorm:"type:uuid;not null;column:pipeline_id"` + PipelineName string `gorm:"type:varchar(255);not null;column:pipeline_name"` + StageBuilds []StageBuild `gorm:"many2many:pipeline_stage_builds;joinForeignKey:PipelineBuildID;joinReferences:StageBuildID"` + CurrentState PipelineExecutionState `gorm:"type:varchar(20);not null;column:pipeline_build_current_state;default:WAITING"` +} + +func (p *PipelineBuild) BeforeCreate(tx *gorm.DB) error { + if p.ID == uuid.Nil { + p.ID = uuid.New() + } + if p.CurrentState == "" { + p.CurrentState = PipelineWaiting + } + return nil +} diff --git a/executor/error/invalidOperationError.go b/executor/error/invalidOperationError.go new file mode 100644 index 00000000..1b4ca18b --- /dev/null +++ b/executor/error/invalidOperationError.go @@ -0,0 +1,20 @@ +package customerror + +// InvalidOperationError is returned when an operation is not permitted given the current state of a resource. +type InvalidOperationError struct { + Message string +} + +func (e *InvalidOperationError) Error() string { + return e.Message +} + +// NewInvalidOperationError creates an InvalidOperationError with the given message. +func NewInvalidOperationError(msg string) *InvalidOperationError { + return &InvalidOperationError{Message: msg} +} + +func (e *InvalidOperationError) Is(target error) bool { + _, ok := target.(*InvalidOperationError) + return ok +} diff --git a/executor/error/notFoundError.go b/executor/error/notFoundError.go new file mode 100644 index 00000000..36641241 --- /dev/null +++ b/executor/error/notFoundError.go @@ -0,0 +1,21 @@ +package customerror + +// NotFoundError is returned when a requested resource does not exist. +type NotFoundError struct { + Message string +} + +func (e *NotFoundError) Error() string { + return e.Message +} + +// NewNotFoundError creates a NotFoundError with the given message. +func NewNotFoundError(msg string) *NotFoundError { + return &NotFoundError{Message: msg} +} + +// Is allows errors.Is() to match any *NotFoundError regardless of Message value. +func (e *NotFoundError) Is(target error) bool { + _, ok := target.(*NotFoundError) + return ok +} diff --git a/executor/go.mod b/executor/go.mod new file mode 100644 index 00000000..4d744862 --- /dev/null +++ b/executor/go.mod @@ -0,0 +1,34 @@ +module github.com/AutoBuilders/AutoBuild/executor + +go 1.27.3 + +require ( + dagger.io/dagger v0.21.11 + github.com/google/uuid v1.6.0 + github.com/joho/godotenv v1.5.1 + gorm.io/driver/sqlite v1.6.0 + gorm.io/gorm v1.31.2 +) + +require ( + github.com/99designs/gqlgen v0.17.89 // indirect + github.com/Khan/genqlient v0.8.1 // indirect + github.com/adrg/xdg v0.5.3 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/dagger/querybuilder v0.0.0-20260402040506-574a5e81cb59 // indirect + github.com/go-logr/logr v1.4.3 // indirect + github.com/go-logr/stdr v1.2.2 // indirect + github.com/jinzhu/inflection v1.0.0 // indirect + github.com/jinzhu/now v1.1.5 // indirect + github.com/mattn/go-sqlite3 v1.14.22 // indirect + github.com/mitchellh/go-homedir v1.1.0 // indirect + github.com/sosodev/duration v1.4.0 // indirect + github.com/vektah/gqlparser/v2 v2.5.32 // indirect + go.opentelemetry.io/auto/sdk v1.2.1 // indirect + go.opentelemetry.io/otel v1.43.0 // indirect + go.opentelemetry.io/otel/metric v1.43.0 // indirect + go.opentelemetry.io/otel/trace v1.43.0 // indirect + golang.org/x/sync v0.20.0 // indirect + golang.org/x/sys v0.42.0 // indirect + golang.org/x/text v0.34.0 // indirect +) diff --git a/executor/go.sum b/executor/go.sum new file mode 100644 index 00000000..d94fa4fc --- /dev/null +++ b/executor/go.sum @@ -0,0 +1,67 @@ +dagger.io/dagger v0.21.11 h1:k16ldA2APuNu5TUY2AChBOPXSNQZZC4ZeTlFcICgRYg= +dagger.io/dagger v0.21.11/go.mod h1:XYoyTW0Op0iokDY17CsYoO2TJEWNwR9JyxuOQMz/2xE= +github.com/99designs/gqlgen v0.17.89 h1:KzEcxPiMgQoMw3m/E85atUEHyZyt0PbAflMia5Kw8z8= +github.com/99designs/gqlgen v0.17.89/go.mod h1:GFqruTVGB7ZTdrf1uzOagpXbY7DrEt1pIxnTdhIbWvQ= +github.com/Khan/genqlient v0.8.1 h1:wtOCc8N9rNynRLXN3k3CnfzheCUNKBcvXmVv5zt6WCs= +github.com/Khan/genqlient v0.8.1/go.mod h1:R2G6DzjBvCbhjsEajfRjbWdVglSH/73kSivC9TLWVjU= +github.com/adrg/xdg v0.5.3 h1:xRnxJXne7+oWDatRhR1JLnvuccuIeCoBu2rtuLqQB78= +github.com/adrg/xdg v0.5.3/go.mod h1:nlTsY+NNiCBGCK2tpm09vRqfVzrc2fLmXGpBLF0zlTQ= +github.com/agnivade/levenshtein v1.2.1 h1:EHBY3UOn1gwdy/VbFwgo4cxecRznFk7fKWN1KOX7eoM= +github.com/agnivade/levenshtein v1.2.1/go.mod h1:QVVI16kDrtSuwcpd0p1+xMC6Z/VfhtCyDIjcwga4/DU= +github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883 h1:bvNMNQO63//z+xNgfBlViaCIJKLlCJ6/fmUseuG0wVQ= +github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/dagger/querybuilder v0.0.0-20260402040506-574a5e81cb59 h1:g6vfdGRyz6fAjfHz5FyYPZgHy8qcQ31fHrBl1iCOzxw= +github.com/dagger/querybuilder v0.0.0-20260402040506-574a5e81cb59/go.mod h1:jsdUJeYzcbyK1j/EqMGPrQgNYxl/Zfg06vvM9C/xXxs= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= +github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= +github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= +github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= +github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= +github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= +github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= +github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= +github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8= +github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I= +github.com/sosodev/duration v1.4.0 h1:35ed0KiVFriGHHzZZJaZLgmTEEICIyt8Sx0RQfj9IjE= +github.com/sosodev/duration v1.4.0/go.mod h1:RQIBBX0+fMLc/D9+Jb/fwvVmo0eZvDDEERAikUR6SDg= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/vektah/gqlparser/v2 v2.5.32 h1:k9QPJd4sEDTL+qB4ncPLflqTJ3MmjB9SrVzJrawpFSc= +github.com/vektah/gqlparser/v2 v2.5.32/go.mod h1:c1I28gSOVNzlfc4WuDlqU7voQnsqI6OG2amkBAFmgts= +go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= +go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= +go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I= +go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0= +go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM= +go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY= +go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A= +go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0= +golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4= +golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo= +golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk= +golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ= +gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8= +gorm.io/gorm v1.31.2 h1:3o8FXNo9v9S858gil+3LlZA1LkCOzgb4g5BL64FgaCo= +gorm.io/gorm v1.31.2/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs= diff --git a/executor/handler/pipelineBuildExecuteHandler.go b/executor/handler/pipelineBuildExecuteHandler.go new file mode 100644 index 00000000..5df255d2 --- /dev/null +++ b/executor/handler/pipelineBuildExecuteHandler.go @@ -0,0 +1,82 @@ +package handler + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + + "github.com/AutoBuilders/AutoBuild/executor/dto" + "github.com/AutoBuilders/AutoBuild/executor/service" +) + +// TODO: It should be only available for local profiles as this payload should be read from message queue + +// PipelineBuildExecutorService is the interface the execute handler uses to start a pipeline build. +type PipelineBuildExecutorService interface { + StartBuild(buildCtx context.Context, pipelineDTO dto.PipelineDTO) (dto.PipelineBuildDTO, bool) +} + +// PipelineBuildExecuteHandler handles HTTP requests that trigger a pipeline build execution. +type PipelineBuildExecuteHandler struct { + srv PipelineBuildExecutorService +} + +// NewPipelineExecuteHandler creates a PipelineBuildExecuteHandler wired to the given executor service. +func NewPipelineExecuteHandler(pipelineBuildExecutorService *service.PipelineBuildExecutorService) *PipelineBuildExecuteHandler { + return &PipelineBuildExecuteHandler{ + srv: pipelineBuildExecutorService, + } +} + +// HandleExecutePipeline accepts a PipelineDTO, validates it, runs the build synchronously, +// and returns the final PipelineBuildDTO or an error response. +func (h *PipelineBuildExecuteHandler) HandleExecutePipeline(w http.ResponseWriter, r *http.Request) { + pipelineDTO, shouldReturn := parsePayload(r, w) + if shouldReturn { + return + } + + fmt.Println("Executing Pipeline ", pipelineDTO.Name) + + pipelineBuildDTO, anyStageBuildFailed := h.srv.StartBuild(context.Background(), pipelineDTO) + + if anyStageBuildFailed { + pipelineBuildDTO.CurrentState = dto.PipelineFailed + writeJSONError(w, "pipeline failed", http.StatusInternalServerError) + } else { + pipelineBuildDTO.CurrentState = dto.PipelineSuccess + writeJSON(w, pipelineBuildDTO) + } +} + +func parsePayload(r *http.Request, w http.ResponseWriter) (dto.PipelineDTO, bool) { + var pipelineDTO dto.PipelineDTO + + err := json.NewDecoder(r.Body).Decode(&pipelineDTO) + if err != nil { + writeJSONError(w, "invalid JSON payload: "+err.Error(), http.StatusBadRequest) + return dto.PipelineDTO{}, true + } + + if validationErr := validatePipelineDTO(pipelineDTO); validationErr != "" { + writeJSONError(w, validationErr, http.StatusBadRequest) + return dto.PipelineDTO{}, true + } + + return pipelineDTO, false +} + +func validatePipelineDTO(p dto.PipelineDTO) string { + seen := make(map[int]bool, len(p.Stages)) + for _, stage := range p.Stages { + if stage.StageOrder < 0 { + return fmt.Sprintf("stage %q has invalid stageOrder %d", stage.Name, stage.StageOrder) + } + if seen[stage.StageOrder] { + return fmt.Sprintf("duplicate stageOrder %d", stage.StageOrder) + } + seen[stage.StageOrder] = true + } + return "" +} diff --git a/executor/handler/pipelineBuildHandler.go b/executor/handler/pipelineBuildHandler.go new file mode 100644 index 00000000..19c0af5e --- /dev/null +++ b/executor/handler/pipelineBuildHandler.go @@ -0,0 +1,89 @@ +package handler + +import ( + "errors" + "net/http" + + customerror "github.com/AutoBuilders/AutoBuild/executor/error" + "github.com/AutoBuilders/AutoBuild/executor/dto" + "github.com/google/uuid" +) + +// PipelineBuildService is the interface the build handler uses to query and delete pipeline builds. +type PipelineBuildService interface { + GetPipelineBuild(id uuid.UUID) (*dto.PipelineBuildDTO, error) + GetAllPipelineBuilds() (*[]dto.PipelineBuildDTO, error) + DeletePipelineBuild(id uuid.UUID) error +} + +// PipelineBuildHandler handles HTTP requests for retrieving and deleting pipeline builds. +type PipelineBuildHandler struct { + srv PipelineBuildService +} + +// NewPipelineBuildHandler creates a PipelineBuildHandler wired to the given service. +func NewPipelineBuildHandler(srv PipelineBuildService) *PipelineBuildHandler { + pipelineBuildHandler := &PipelineBuildHandler{ + srv: srv, + } + + return pipelineBuildHandler +} + +// HandleGetPipelineBuild retrieves a single PipelineBuild by ID from the path parameter. +func (pbh *PipelineBuildHandler) HandleGetPipelineBuild(w http.ResponseWriter, r *http.Request) { + id, err := uuid.Parse(r.PathValue("pipelineBuildId")) + if err != nil { + writeJSONError(w, "invalid pipeline build id", http.StatusBadRequest) + return + } + + pb, err := pbh.srv.GetPipelineBuild(id) + if err != nil { + var nfe *customerror.NotFoundError + if errors.As(err, &nfe) { + writeJSONError(w, nfe.Message, http.StatusNotFound) + } else { + writeJSONError(w, "internal server error", http.StatusInternalServerError) + } + return + } + + writeJSON(w, pb) +} + +// HandleGetAllPipelineBuilds retrieves all PipelineBuilds. +func (pbh *PipelineBuildHandler) HandleGetAllPipelineBuilds(w http.ResponseWriter, r *http.Request) { + pbs, err := pbh.srv.GetAllPipelineBuilds() + if err != nil { + writeJSONError(w, "internal server error", http.StatusInternalServerError) + return + } + + writeJSON(w, pbs) +} + +// HandleDeletePipelineBuild deletes a PipelineBuild by ID. +// Returns 404 if not found, 422 if the build is currently in progress. +func (pbh *PipelineBuildHandler) HandleDeletePipelineBuild(w http.ResponseWriter, r *http.Request) { + id, err := uuid.Parse(r.PathValue("pipelineBuildId")) + if err != nil { + writeJSONError(w, "invalid pipeline build id", http.StatusBadRequest) + return + } + + if err := pbh.srv.DeletePipelineBuild(id); err != nil { + var nfe *customerror.NotFoundError + var ioe *customerror.InvalidOperationError + if errors.As(err, &nfe) { + writeJSONError(w, nfe.Message, http.StatusNotFound) + } else if errors.As(err, &ioe) { + writeJSONError(w, ioe.Message, http.StatusUnprocessableEntity) + } else { + writeJSONError(w, "internal server error", http.StatusInternalServerError) + } + return + } + + w.WriteHeader(http.StatusNoContent) +} diff --git a/executor/handler/registerHandlers.go b/executor/handler/registerHandlers.go new file mode 100644 index 00000000..19ff0021 --- /dev/null +++ b/executor/handler/registerHandlers.go @@ -0,0 +1,59 @@ +package handler + +import ( + "encoding/json" + "fmt" + "log" + "net/http" + + "github.com/AutoBuilders/AutoBuild/executor/dto" + "github.com/AutoBuilders/AutoBuild/executor/mapper" + "github.com/AutoBuilders/AutoBuild/executor/repository" + "github.com/AutoBuilders/AutoBuild/executor/runner" + "github.com/AutoBuilders/AutoBuild/executor/service" +) + +func writeJSON(w http.ResponseWriter, body any) { + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(body) +} + +func writeJSONError(w http.ResponseWriter, msg string, status int) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + json.NewEncoder(w).Encode(map[string]string{"error": msg}) +} + +// RegisterHandlers wires all HTTP routes to their handlers on the given mux. +func RegisterHandlers(mux *http.ServeMux, repo *repository.PipelineBuildRepository) { + //TODO: Block it behind local profile.. it should be only activated for local profile + // mux.HandleFunc(executePipelineHttpMethod+" "+executePipelineUrl, handleExecutePipeline(repo)) + runner := runner.SetupDaggerClient() // TODO: inject it from outside + pipelineBuildExecutorService := service.NewPipelineBuildExecutorService(func(pbd dto.PipelineBuildDTO) { + + pb := mapper.PipelineBuildFromDTO(pbd) + + if err := repo.Save(pb); err != nil { + log.Printf("failed to persist pipeline build: %v", err) + } + + fmt.Println("-------------------------------") + b, _ := json.MarshalIndent(pbd, "", " ") + fmt.Println("Build snapshot:", string(b)) + fmt.Println("-------------------------------") + }, runner) + + pipelineBuildExecuteHandler := NewPipelineExecuteHandler(pipelineBuildExecutorService) + mux.HandleFunc("POST /api/v1/execute/pipeline", pipelineBuildExecuteHandler.HandleExecutePipeline) + + pipelineService := service.NewPipelineBuildService(repo) + pipelineBuildHandler := NewPipelineBuildHandler(pipelineService) + + mux.HandleFunc("GET /api/v1/pipeline/build/{pipelineBuildId}", pipelineBuildHandler.HandleGetPipelineBuild) + mux.HandleFunc("GET /api/v1/pipeline/build/{$}", pipelineBuildHandler.HandleGetAllPipelineBuilds) + mux.HandleFunc("DELETE /api/v1/pipeline/build/{pipelineBuildId}", pipelineBuildHandler.HandleDeletePipelineBuild) + + stageBuildLogsService := service.NewStageBuildLogsService(repo) + stageBuildLogsHandler := NewStageBuildLogsHandler(stageBuildLogsService) + mux.HandleFunc("GET /api/v1/stage/build/logs/{stageBuildId}", stageBuildLogsHandler.HandleGetStageBuildLogs) +} diff --git a/executor/handler/stageBuildLogsHandler.go b/executor/handler/stageBuildLogsHandler.go new file mode 100644 index 00000000..aa2f0429 --- /dev/null +++ b/executor/handler/stageBuildLogsHandler.go @@ -0,0 +1,47 @@ +package handler + +import ( + "errors" + "net/http" + + customerror "github.com/AutoBuilders/AutoBuild/executor/error" + "github.com/google/uuid" +) + +// StageBuildLogsService is the interface the logs handler uses to retrieve stage build logs. +type StageBuildLogsService interface { + GetStageBuildLogs(id uuid.UUID) (map[string]string, error) +} + +// StageBuildLogsHandler handles HTTP requests for retrieving stage build log output. +type StageBuildLogsHandler struct { + srv StageBuildLogsService +} + +// NewStageBuildLogsHandler creates a StageBuildLogsHandler wired to the given service. +func NewStageBuildLogsHandler(srv StageBuildLogsService) *StageBuildLogsHandler { + return &StageBuildLogsHandler{srv: srv} +} + +// HandleGetStageBuildLogs retrieves the log output for a stage build by ID from the path parameter. +// Returns 404 if the stage build does not exist. +func (h *StageBuildLogsHandler) HandleGetStageBuildLogs(w http.ResponseWriter, r *http.Request) { + id, err := uuid.Parse(r.PathValue("stageBuildId")) + if err != nil { + writeJSONError(w, "invalid stage build id", http.StatusBadRequest) + return + } + + logs, err := h.srv.GetStageBuildLogs(id) + if err != nil { + var nfe *customerror.NotFoundError + if errors.As(err, &nfe) { + writeJSONError(w, nfe.Message, http.StatusNotFound) + } else { + writeJSONError(w, "internal server error", http.StatusInternalServerError) + } + return + } + + writeJSON(w, logs) +} diff --git a/executor/main.go b/executor/main.go new file mode 100644 index 00000000..f4dbea25 --- /dev/null +++ b/executor/main.go @@ -0,0 +1,27 @@ +package main + +import ( + "log" + "net/http" + "os" + + "github.com/AutoBuilders/AutoBuild/executor/config" + "github.com/AutoBuilders/AutoBuild/executor/handler" + "github.com/AutoBuilders/AutoBuild/executor/repository" +) + +func main() { + config.LoadProfile() + + repo := repository.NewPipelineBuildRepository(os.Getenv("EXECUTOR_DB_DSN")) + + mux := http.NewServeMux() + + handler.RegisterHandlers(mux, repo) + serverPortAddr, server := config.InitServer(mux) + + log.Println("Server listening on http://localhost", serverPortAddr) + if err := server.ListenAndServe(); err != nil { + log.Fatalf("Server failed: %s", err) + } +} diff --git a/executor/mapper/mapper.go b/executor/mapper/mapper.go new file mode 100644 index 00000000..b65b0425 --- /dev/null +++ b/executor/mapper/mapper.go @@ -0,0 +1,71 @@ +package mapper + +import ( + "path/filepath" + + "github.com/AutoBuilders/AutoBuild/executor/dto" + "github.com/AutoBuilders/AutoBuild/executor/entity" + "github.com/google/uuid" +) + +// logDir is relative to the executor binary location, matching the convention in daggerRunner.go. +const logDir = "../pipeline_build_logs" + +// StageBuildLogPath returns the conventional log file path for a stage build. +func StageBuildLogPath(pipelineBuildID, stageBuildID uuid.UUID) string { + return filepath.Join(logDir, pipelineBuildID.String(), stageBuildID.String()+".log") +} + +// StageBuildToDTO converts a StageBuild entity to a StageBuildDTO. +func StageBuildToDTO(sb entity.StageBuild, stageName string) dto.StageBuildDTO { + return dto.StageBuildDTO{ + Id: sb.ID, + StageId: sb.StageID, + StageName: sb.StageName, + StageOrder: sb.StageOrder, + CurrentState: dto.StageExecutionState(sb.CurrentState), + } +} + +// StageBuildFromDTO converts a StageBuildDTO to a StageBuild entity. +// The log file path is derived from the pipeline build ID and stage build ID. +func StageBuildFromDTO(d dto.StageBuildDTO, pipelineBuildID uuid.UUID) entity.StageBuild { + return entity.StageBuild{ + ID: d.Id, + StageID: d.StageId, + StageName: d.StageName, + StageOrder: d.StageOrder, + CurrentState: entity.StageExecutionState(d.CurrentState), + LogPath: StageBuildLogPath(pipelineBuildID, d.Id), + } +} + +// PipelineBuildToDTO converts a PipelineBuild entity to a PipelineBuildDTO. +func PipelineBuildToDTO(pb entity.PipelineBuild) dto.PipelineBuildDTO { + stageBuilds := make([]dto.StageBuildDTO, len(pb.StageBuilds)) + for i, sb := range pb.StageBuilds { + stageBuilds[i] = StageBuildToDTO(sb, "") + } + return dto.PipelineBuildDTO{ + Id: pb.ID, + PipelineId: pb.PipelineID, + PipelineName: pb.PipelineName, + CurrentState: dto.PipelineExecutionState(pb.CurrentState), + StageBuilds: stageBuilds, + } +} + +// PipelineBuildFromDTO converts a PipelineBuildDTO to a PipelineBuild entity. +func PipelineBuildFromDTO(d dto.PipelineBuildDTO) entity.PipelineBuild { + stageBuilds := make([]entity.StageBuild, len(d.StageBuilds)) + for i, sb := range d.StageBuilds { + stageBuilds[i] = StageBuildFromDTO(sb, d.Id) + } + return entity.PipelineBuild{ + ID: d.Id, + PipelineID: d.PipelineId, + PipelineName: d.PipelineName, + CurrentState: entity.PipelineExecutionState(d.CurrentState), + StageBuilds: stageBuilds, + } +} diff --git a/executor/repository/repository.go b/executor/repository/repository.go new file mode 100644 index 00000000..a8f40f6e --- /dev/null +++ b/executor/repository/repository.go @@ -0,0 +1,71 @@ +package repository + +import ( + "log" + + "github.com/AutoBuilders/AutoBuild/executor/entity" + "github.com/google/uuid" + "gorm.io/driver/sqlite" + "gorm.io/gorm" +) + +// PipelineBuildRepository provides persistence operations for PipelineBuild and StageBuild entities. +type PipelineBuildRepository struct { + db *gorm.DB +} + +// NewPipelineBuildRepository initialises a new PipelineBuildRepository backed by a SQLite database at the given DSN. +func NewPipelineBuildRepository(dsn string) *PipelineBuildRepository { + db := initDB(dsn) + return &PipelineBuildRepository{db: db} +} + +func initDB(dsn string) *gorm.DB { + // TODO: make db generic. It should be able to take any db and it's corresponding dsn. + db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{}) + if err != nil { + log.Fatalf("failed to connect to database: %v", err) + } + + if err := db.AutoMigrate(&entity.StageBuild{}, &entity.PipelineBuild{}, &entity.PipelineStageBuild{}); err != nil { + log.Fatalf("failed to auto-migrate: %v", err) + } + + return db +} + +// Save upserts a PipelineBuild and its associated StageBuilds in a single transaction. +func (r *PipelineBuildRepository) Save(pb entity.PipelineBuild) error { + return r.db.Transaction(func(tx *gorm.DB) error { + if err := tx.Session(&gorm.Session{FullSaveAssociations: true}).Save(&pb).Error; err != nil { + return err + } + return tx.Model(&pb).Association("StageBuilds").Replace(pb.StageBuilds) + }) +} + +// FindByID retrieves a PipelineBuild by its ID, preloading its StageBuilds. +func (r *PipelineBuildRepository) FindByID(id uuid.UUID) (entity.PipelineBuild, error) { + var pb entity.PipelineBuild + err := r.db.Preload("StageBuilds").First(&pb, "id = ?", id).Error + return pb, err +} + +// FindAll retrieves all PipelineBuilds, preloading their StageBuilds. +func (r *PipelineBuildRepository) FindAll() ([]entity.PipelineBuild, error) { + var pbs []entity.PipelineBuild + err := r.db.Preload("StageBuilds").Find(&pbs).Error + return pbs, err +} + +// Delete removes a PipelineBuild by its ID. +func (r *PipelineBuildRepository) Delete(id uuid.UUID) error { + return r.db.Delete(&entity.PipelineBuild{}, "id = ?", id).Error +} + +// FindStageBuildByID retrieves a StageBuild by its ID. +func (r *PipelineBuildRepository) FindStageBuildByID(id uuid.UUID) (entity.StageBuild, error) { + var sb entity.StageBuild + err := r.db.First(&sb, "id = ?", id).Error + return sb, err +} diff --git a/executor/runner/client.go b/executor/runner/client.go new file mode 100644 index 00000000..0c6f1efc --- /dev/null +++ b/executor/runner/client.go @@ -0,0 +1,22 @@ +package runner + +import ( + "context" + "os" + + "dagger.io/dagger" +) + +// SetupDaggerClient initialises a Dagger client and returns a DaggerRunner backed by it. +// Panics if the Dagger engine cannot be reached. +func SetupDaggerClient() *DaggerRunner { + ctx := context.Background() + // 1. Initialize the Dagger client + client, err := dagger.Connect(ctx, dagger.WithLogOutput(os.Stdout)) + if err != nil { + panic(err) + } + // return ctx, client + + return NewDaggerRunner(client) +} diff --git a/executor/runner/daggerRunner.go b/executor/runner/daggerRunner.go new file mode 100644 index 00000000..0c532e58 --- /dev/null +++ b/executor/runner/daggerRunner.go @@ -0,0 +1,154 @@ +package runner + +import ( + "context" + "fmt" + "log" + "os" + "path/filepath" + "sort" + + "dagger.io/dagger" + + "github.com/AutoBuilders/AutoBuild/executor/dto" + "github.com/AutoBuilders/AutoBuild/executor/mapper" + "github.com/google/uuid" +) + +// DaggerRunner executes pipeline builds inside Dagger containers. +type DaggerRunner struct { + client *dagger.Client +} + +// NewDaggerRunner creates a DaggerRunner using the provided Dagger client. +func NewDaggerRunner(client *dagger.Client) *DaggerRunner { + return &DaggerRunner{ + client: client, + } +} + +// StartBuild executes the pipeline stages in order inside a Dagger container. +// Stages are sorted by StageOrder before execution. If a stage fails, all subsequent stages +// are marked STOPPED. The notify callback is called on every state transition. +// Returns the final PipelineBuildDTO and true if any stage failed. +func (dr *DaggerRunner) StartBuild(buildCtx context.Context, pipelineDTO dto.PipelineDTO, notify func(dto.PipelineBuildDTO)) (dto.PipelineBuildDTO, bool) { + container, pipelineBuildDTO, anyStageBuildFailed, err := dr.initBuild(dr.client, pipelineDTO, notify) + if err != nil { + pipelineBuildDTO.CurrentState = dto.PipelineFailed + notify(pipelineBuildDTO) + return pipelineBuildDTO, true + } + + // execute per stage in the container + for i, stage := range pipelineDTO.Stages { + stageBuild := &pipelineBuildDTO.StageBuilds[i] + + if anyStageBuildFailed { + stageBuild.CurrentState = dto.StageStopped + notify(pipelineBuildDTO) + continue + } + + stageBuild.CurrentState = dto.StageRunning + notify(pipelineBuildDTO) + + scriptPath := fmt.Sprintf("/tmp/script_%s.sh", stage.Name) + stageContainer := container.WithNewFile(scriptPath, stage.Command, dagger.ContainerWithNewFileOpts{ + Permissions: 0755, + }).WithExec([]string{"sh", "-e", scriptPath}, dagger.ContainerWithExecOpts{ + Expect: dagger.ReturnTypeAny, + }) + + stdout, _ := stageContainer.Stdout(buildCtx) + stderr, _ := stageContainer.Stderr(buildCtx) + exitCode, exitErr := stageContainer.ExitCode(buildCtx) + + // TODO: abstract it behind a log store which for local will be simply file + logPath := mapper.StageBuildLogPath(pipelineBuildDTO.Id, stageBuild.Id) + logFile, fileErr := os.Create(logPath) + if fileErr != nil { + log.Printf("failed to create log file for stage %s at %s: %v", stageBuild.Id, logPath, fileErr) + } else { + if stdout != "" { + if _, writeErr := fmt.Fprint(logFile, stdout); writeErr != nil { + log.Printf("failed to write stdout for stage %s at %s: %v", stageBuild.Id, logPath, writeErr) + } + } + if stderr != "" { + if _, writeErr := fmt.Fprint(logFile, stderr); writeErr != nil { + log.Printf("failed to write stderr for stage %s at %s: %v", stageBuild.Id, logPath, writeErr) + } + } + if closeErr := logFile.Close(); closeErr != nil { + log.Printf("failed to close log file for stage %s at %s: %v", stageBuild.Id, logPath, closeErr) + } + } + + stageFailed := exitErr != nil || exitCode != 0 + if stageFailed { + anyStageBuildFailed = true + stageBuild.CurrentState = dto.StageFailed + notify(pipelineBuildDTO) + continue + } + + stageBuild.CurrentState = dto.StageSuccess + notify(pipelineBuildDTO) + } + + if !anyStageBuildFailed { + pipelineBuildDTO.CurrentState = dto.PipelineSuccess + } else { + pipelineBuildDTO.CurrentState = dto.PipelineFailed + } + + notify(pipelineBuildDTO) + + return pipelineBuildDTO, anyStageBuildFailed +} + +func (dr *DaggerRunner) initBuild(client *dagger.Client, pipelineDTO dto.PipelineDTO, notify func(dto.PipelineBuildDTO)) (*dagger.Container, dto.PipelineBuildDTO, bool, error) { + container := client.Container().From("alpine").WithWorkdir("/src") + + sort.Slice(pipelineDTO.Stages, func(i, j int) bool { + return pipelineDTO.Stages[i].StageOrder < pipelineDTO.Stages[j].StageOrder + }) + pipelineBuildDTO := initializePipelineBuild(pipelineDTO) + notify(pipelineBuildDTO) + + logDir := filepath.Join("..", "pipeline_build_logs", pipelineBuildDTO.Id.String()) + if err := os.MkdirAll(logDir, 0755); err != nil { + return nil, pipelineBuildDTO, false, fmt.Errorf("failed to create log directory: %w", err) + } + + pipelineBuildDTO.CurrentState = dto.PipelineRunning + notify(pipelineBuildDTO) + + return container, pipelineBuildDTO, false, nil +} + +func initializePipelineBuild(pipelineDTO dto.PipelineDTO) dto.PipelineBuildDTO { + pipelineBuildId, _ := uuid.NewV7() + pipelineBuildDTO := dto.PipelineBuildDTO{ + Id: pipelineBuildId, + PipelineId: pipelineDTO.Id, + PipelineName: pipelineDTO.Name, + CurrentState: dto.PipelineWaiting, + StageBuilds: []dto.StageBuildDTO{}, + } + + for _, stageDTO := range pipelineDTO.Stages { + stageBuildId, _ := uuid.NewV7() + stageBuildDTO := dto.StageBuildDTO{ + Id: stageBuildId, + StageId: stageDTO.Id, + StageName: stageDTO.Name, + StageOrder: stageDTO.StageOrder, + CurrentState: dto.StageWaiting, + } + + pipelineBuildDTO.StageBuilds = append(pipelineBuildDTO.StageBuilds, stageBuildDTO) + } + + return pipelineBuildDTO +} diff --git a/executor/service/pipelineBuildExecutorService.go b/executor/service/pipelineBuildExecutorService.go new file mode 100644 index 00000000..84cf3530 --- /dev/null +++ b/executor/service/pipelineBuildExecutorService.go @@ -0,0 +1,34 @@ +package service + +import ( + "context" + + "github.com/AutoBuilders/AutoBuild/executor/dto" +) + +// Runner is the interface the executor service uses to run a pipeline build. +type Runner interface { + StartBuild(buildCtx context.Context, pipelineDTO dto.PipelineDTO, notify func(dto.PipelineBuildDTO)) (dto.PipelineBuildDTO, bool) +} + +// PipelineBuildExecutorService orchestrates pipeline builds by delegating to a Runner and notifying on state changes. +type PipelineBuildExecutorService struct { + notify func(dto.PipelineBuildDTO) // TODO: have an error returned in case of failures + runner Runner +} + +// NewPipelineBuildExecutorService creates a PipelineBuildExecutorService with the given notify callback and runner. +// The notify callback is invoked on every state transition during a build. +func NewPipelineBuildExecutorService(notify func(dto.PipelineBuildDTO), runnerClient Runner) *PipelineBuildExecutorService { + return &PipelineBuildExecutorService{ + notify: notify, + runner: runnerClient, + } +} + +// StartBuild delegates execution to the underlying Runner and returns the final build state and whether any stage failed. +func (es *PipelineBuildExecutorService) StartBuild(buildCtx context.Context, pipelineDTO dto.PipelineDTO) (dto.PipelineBuildDTO, bool) { + // TODO: error handling + // TODO: Instead of returning boolean try throwing error and handling it which will make it explicit + return es.runner.StartBuild(buildCtx, pipelineDTO, es.notify) +} diff --git a/executor/service/pipelineBuildService.go b/executor/service/pipelineBuildService.go new file mode 100644 index 00000000..ebc52cea --- /dev/null +++ b/executor/service/pipelineBuildService.go @@ -0,0 +1,80 @@ +package service + +import ( + "errors" + + "github.com/google/uuid" + + "github.com/AutoBuilders/AutoBuild/executor/dto" + customerror "github.com/AutoBuilders/AutoBuild/executor/error" + "github.com/AutoBuilders/AutoBuild/executor/mapper" + "github.com/AutoBuilders/AutoBuild/executor/repository" + "gorm.io/gorm" +) + +// PipelineBuildService provides query and deletion operations for pipeline build records. +type PipelineBuildService struct { + db *repository.PipelineBuildRepository +} + +// NewPipelineBuildService creates a PipelineBuildService backed by the given repository. +func NewPipelineBuildService(db *repository.PipelineBuildRepository) *PipelineBuildService { + return &PipelineBuildService{ + db: db, + } +} + +// GetPipelineBuild retrieves a PipelineBuild by ID. Returns NotFoundError if the build does not exist. +func (s *PipelineBuildService) GetPipelineBuild(id uuid.UUID) (*dto.PipelineBuildDTO, error) { + pb, err := s.db.FindByID(id) + + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return nil, customerror.NewNotFoundError("PipelineBuild with id " + id.String() + " not found") + } + + return nil, errors.New("Unexpected error ocurred finding PipelineBuild with Id " + id.String()) + } + + pbDto := mapper.PipelineBuildToDTO(pb) + return &pbDto, nil +} + +// GetAllPipelineBuilds retrieves all PipelineBuilds. +func (s *PipelineBuildService) GetAllPipelineBuilds() (*[]dto.PipelineBuildDTO, error) { + pbs, err := s.db.FindAll() + + if err != nil { + return nil, errors.New("Unexpected error ocurred finding PipelineBuilds") + } + + dtos := make([]dto.PipelineBuildDTO, len(pbs)) + for i, pb := range pbs { + dtos[i] = mapper.PipelineBuildToDTO(pb) + } + + return &dtos, nil +} + +// DeletePipelineBuild deletes a PipelineBuild by ID. +// Returns NotFoundError if the build does not exist, or InvalidOperationError if the build is currently in progress. +func (s *PipelineBuildService) DeletePipelineBuild(id uuid.UUID) error { + pb, err := s.GetPipelineBuild(id) + + if err != nil { + return err + } + + // TODO: Abandoned builds stuck in in-progress status will not be removed in this way. need to add a step at the time of application startup to clean up such builds or forcefully keep their statuses to STOPPED to ensure easier cleanups. + if pb.CurrentState == dto.PipelineWaiting || pb.CurrentState == dto.PipelineRunning { + return customerror.NewInvalidOperationError("cannot delete pipeline build " + id.String() + " while it is in progress") + } + + err = s.db.Delete(id) + + if err != nil { + return errors.New("Unexpected error ocurred finding PipelineBuilds") + } + + return nil +} diff --git a/executor/service/stageBuildLogsService.go b/executor/service/stageBuildLogsService.go new file mode 100644 index 00000000..8bde7f43 --- /dev/null +++ b/executor/service/stageBuildLogsService.go @@ -0,0 +1,59 @@ +package service + +import ( + "errors" + "fmt" + "os" + + "github.com/AutoBuilders/AutoBuild/executor/entity" + customerror "github.com/AutoBuilders/AutoBuild/executor/error" + "github.com/AutoBuilders/AutoBuild/executor/repository" + "github.com/google/uuid" + "gorm.io/gorm" +) + +// StageBuildLogsService retrieves log output for stage builds. +type StageBuildLogsService struct { + db *repository.PipelineBuildRepository +} + +// NewStageBuildLogsService creates a StageBuildLogsService backed by the given repository. +func NewStageBuildLogsService(db *repository.PipelineBuildRepository) *StageBuildLogsService { + return &StageBuildLogsService{db: db} +} + +// GetStageBuildLogs returns the log output for a stage build. +// Returns an empty log for STOPPED stages. Returns NotFoundError if the stage build does not exist. +func (s *StageBuildLogsService) GetStageBuildLogs(id uuid.UUID) (map[string]string, error) { + sb, err := s.db.FindStageBuildByID(id) + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return nil, customerror.NewNotFoundError("StageBuild with id " + id.String() + " not found") + } + return nil, errors.New("unexpected error finding StageBuild with id " + id.String()) + } + + if sb.CurrentState == entity.StageStopped { + return map[string]string{"log": ""}, nil + } + + logs, err := readLogFile(sb) + if err != nil { + return nil, err + } + + return map[string]string{"log": logs}, nil +} + +func readLogFile(sb entity.StageBuild) (string, error) { + if sb.LogPath == "" { + return "", errors.New("no log path set for StageBuild " + sb.ID.String()) + } + + data, err := os.ReadFile(sb.LogPath) + if err != nil { + return "", fmt.Errorf("failed to read log file for StageBuild %s: %w", sb.ID.String(), err) + } + + return string(data), nil +}