Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

publish ai summaries #1864

Merged
merged 8 commits into from
Dec 30, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 27 additions & 3 deletions backend/controllers/github.go
Original file line number Diff line number Diff line change
Expand Up @@ -511,7 +511,18 @@ func handlePullRequestEvent(gh utils.GithubClientProvider, payload *github.PullR
log.Printf("strconv.ParseInt error: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: could not handle commentId: %v", err))
}
batchId, _, err := utils.ConvertJobsToDiggerJobs(*diggerCommand, models.DiggerVCSGithub, organisationId, impactedJobsMap, impactedProjectsMap, projectsGraph, installationId, branch, prNumber, repoOwner, repoName, repoFullName, commitSha, commentId, diggerYmlStr, 0)

var aiSummaryCommentId = ""
if config.Reporting.AiSummary {
aiSummaryComment, err := ghService.PublishComment(prNumber, "AI Summary will be posted here after completion")
if err != nil {
log.Printf("could not post ai summary comment: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: could not post ai comment summary comment id: %v", err))
}
aiSummaryCommentId = aiSummaryComment.Id
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Check for nil after failing to publish the AI summary comment.

If PublishComment fails, we log the error but still proceed to use aiSummaryComment.Id, which may cause a nil pointer dereference. Consider returning early when an error occurs.

Proposed fix:

 var aiSummaryCommentId = ""
 if config.Reporting.AiSummary {
     aiSummaryComment, err := ghService.PublishComment(prNumber, "AI Summary will be posted here after completion")
     if err != nil {
         log.Printf("could not post ai summary comment: %v", err)
         commentReporterManager.UpdateComment(fmt.Sprintf(":x: could not post ai comment summary comment id: %v", err))
+        return
     }
     aiSummaryCommentId = aiSummaryComment.Id
 }

Committable suggestion skipped: line range outside the PR's diff.

batchId, _, err := utils.ConvertJobsToDiggerJobs(*diggerCommand, models.DiggerVCSGithub, organisationId, impactedJobsMap, impactedProjectsMap, projectsGraph, installationId, branch, prNumber, repoOwner, repoName, repoFullName, commitSha, commentId, diggerYmlStr, 0, aiSummaryCommentId, config.ReportTerraformOutputs)
if err != nil {
log.Printf("ConvertJobsToDiggerJobs error: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: ConvertJobsToDiggerJobs error: %v", err))
Expand Down Expand Up @@ -768,7 +779,10 @@ func handleIssueCommentEvent(gh utils.GithubClientProvider, payload *github.Issu
// terraform code generator
if os.Getenv("DIGGER_GENERATION_ENABLED") == "1" {
err = GenerateTerraformFromCode(payload, commentReporterManager, config, defaultBranch, ghService, repoOwner, repoName, commitSha, issueNumber, branch)
return err
if err != nil {
log.Printf("terraform generation failed: %v", err)
return err
}
}

commentIdStr := strconv.FormatInt(userCommentId, 10)
Expand Down Expand Up @@ -902,7 +916,17 @@ func handleIssueCommentEvent(gh utils.GithubClientProvider, payload *github.Issu
return fmt.Errorf("comment reporter error: %v", err)
}

batchId, _, err := utils.ConvertJobsToDiggerJobs(*diggerCommand, "github", orgId, impactedProjectsJobMap, impactedProjectsMap, projectsGraph, installationId, *branch, issueNumber, repoOwner, repoName, repoFullName, *commitSha, reporterCommentId, diggerYmlStr, 0)
var aiSummaryCommentId = ""
if config.Reporting.AiSummary {
aiSummaryComment, err := ghService.PublishComment(issueNumber, "AI Summary will be posted here after completion")
if err != nil {
log.Printf("could not post ai summary comment: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: could not post ai comment summary comment id: %v", err))
}
aiSummaryCommentId = aiSummaryComment.Id
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Check for nil after failing to publish the AI summary comment.

Similarly to the earlier comment, if PublishComment fails, referencing aiSummaryComment.Id may cause a panic.

Proposed fix:

 var aiSummaryCommentId = ""
 if config.Reporting.AiSummary {
     aiSummaryComment, err := ghService.PublishComment(issueNumber, "AI Summary will be posted here after completion")
     if err != nil {
         log.Printf("could not post ai summary comment: %v", err)
         commentReporterManager.UpdateComment(fmt.Sprintf(":x: could not post ai comment summary comment id: %v", err))
+        return
     }
     aiSummaryCommentId = aiSummaryComment.Id
 }

Committable suggestion skipped: line range outside the PR's diff.

batchId, _, err := utils.ConvertJobsToDiggerJobs(*diggerCommand, "github", orgId, impactedProjectsJobMap, impactedProjectsMap, projectsGraph, installationId, *branch, issueNumber, repoOwner, repoName, repoFullName, *commitSha, reporterCommentId, diggerYmlStr, 0, aiSummaryCommentId, config.ReportTerraformOutputs)
if err != nil {
log.Printf("ConvertJobsToDiggerJobs error: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: ConvertJobsToDiggerJobs error: %v", err))
Expand Down
8 changes: 4 additions & 4 deletions backend/controllers/github_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -731,7 +731,7 @@ func TestJobsTreeWithOneJobsAndTwoProjects(t *testing.T) {
graph, err := configuration.CreateProjectDependencyGraph(projects)
assert.NoError(t, err)

_, result, err := utils.ConvertJobsToDiggerJobs("", "github", 1, jobs, projectMap, graph, 41584295, "", 2, "diggerhq", "parallel_jobs_demo", "diggerhq/parallel_jobs_demo", "", 123, "test", 0)
_, result, err := utils.ConvertJobsToDiggerJobs("", "github", 1, jobs, projectMap, graph, 41584295, "", 2, "diggerhq", "parallel_jobs_demo", "diggerhq/parallel_jobs_demo", "", 123, "test", 0, "", false)
assert.NoError(t, err)
assert.Equal(t, 1, len(result))
parentLinks, err := models.DB.GetDiggerJobParentLinksChildId(&result["dev"].DiggerJobID)
Expand Down Expand Up @@ -760,7 +760,7 @@ func TestJobsTreeWithTwoDependantJobs(t *testing.T) {
projectMap["dev"] = project1
projectMap["prod"] = project2

_, result, err := utils.ConvertJobsToDiggerJobs("", "github", 1, jobs, projectMap, graph, 123, "", 2, "", "", "test", "", 123, "test", 0)
_, result, err := utils.ConvertJobsToDiggerJobs("", "github", 1, jobs, projectMap, graph, 123, "", 2, "", "", "test", "", 123, "test", 0, "", false)
assert.NoError(t, err)
assert.Equal(t, 2, len(result))

Expand Down Expand Up @@ -793,7 +793,7 @@ func TestJobsTreeWithTwoIndependentJobs(t *testing.T) {
projectMap["dev"] = project1
projectMap["prod"] = project2

_, result, err := utils.ConvertJobsToDiggerJobs("", "github", 1, jobs, projectMap, graph, 123, "", 2, "", "", "test", "", 123, "test", 0)
_, result, err := utils.ConvertJobsToDiggerJobs("", "github", 1, jobs, projectMap, graph, 123, "", 2, "", "", "test", "", 123, "test", 0, "", false)
assert.NoError(t, err)
assert.Equal(t, 2, len(result))
parentLinks, err := models.DB.GetDiggerJobParentLinksChildId(&result["dev"].DiggerJobID)
Expand Down Expand Up @@ -838,7 +838,7 @@ func TestJobsTreeWithThreeLevels(t *testing.T) {
projectMap["555"] = project5
projectMap["666"] = project6

_, result, err := utils.ConvertJobsToDiggerJobs("", "github", 1, jobs, projectMap, graph, 123, "", 2, "", "", "test", "", 123, "test", 0)
_, result, err := utils.ConvertJobsToDiggerJobs("", "github", 1, jobs, projectMap, graph, 123, "", 2, "", "", "test", "", 123, "test", 0, "", false)
assert.NoError(t, err)
assert.Equal(t, 6, len(result))
parentLinks, err := models.DB.GetDiggerJobParentLinksChildId(&result["111"].DiggerJobID)
Expand Down
68 changes: 59 additions & 9 deletions backend/controllers/projects.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"gorm.io/gorm"
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
Expand Down Expand Up @@ -323,7 +324,6 @@ type SetJobStatusRequest struct {
Footprint *iac_utils.IacPlanFootprint `json:"job_plan_footprint"`
PrCommentUrl string `json:"pr_comment_url"`
TerraformOutput string `json:"terraform_output"`

}

func (d DiggerController) SetJobStatusForProject(c *gin.Context) {
Expand Down Expand Up @@ -482,6 +482,12 @@ func (d DiggerController) SetJobStatusForProject(c *gin.Context) {
return
}

err = CreateTerraformOutputsSummary(d.GithubClientProvider, batch)
if err != nil {
log.Printf("could not generate terraform plans summary: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "could not generate terraform plans summary"})
}

err = AutomergePRforBatchIfEnabled(d.GithubClientProvider, batch)
if err != nil {
log.Printf("Error merging PR with automerge option: %v", err)
Expand All @@ -493,7 +499,6 @@ func (d DiggerController) SetJobStatusForProject(c *gin.Context) {
if err != nil {
log.Printf("Error getting batch details: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error getting batch details"})

}

UpdateCommentsForBatchGroup(d.GithubClientProvider, batch, res.Jobs)
Expand Down Expand Up @@ -648,6 +653,58 @@ func GetPrServiceFromBatch(batch *models.DiggerBatch, gh utils.GithubClientProvi
return nil, fmt.Errorf("could not retrieive a service for %v", batch.VCS)
}

func CreateTerraformOutputsSummary(gh utils.GithubClientProvider, batch *models.DiggerBatch) error {
diggerYmlString := batch.DiggerConfig
diggerConfigYml, err := digger_config.LoadDiggerConfigYamlFromString(diggerYmlString)
if err != nil {
log.Printf("Error loading digger config from batch: %v", err)
return fmt.Errorf("error loading digger config from batch: %v", err)
}

config, _, err := digger_config.ConvertDiggerYamlToConfig(diggerConfigYml)

if batch.Status == orchestrator_scheduler.BatchJobSucceeded && config.Reporting.AiSummary == true {
prService, err := GetPrServiceFromBatch(batch, gh)
if err != nil {
log.Printf("Error getting github service: %v", err)
return fmt.Errorf("error getting github service: %v", err)
}

summaryEndpoint := os.Getenv("DIGGER_AI_SUMMARY_ENDPOINT")
if summaryEndpoint == "" {
log.Printf("could not generate AI summary, ai summary endpoint missing")
return fmt.Errorf("could not generate AI summary, ai summary endpoint missing")
}
apiToken := os.Getenv("DIGGER_AI_SUMMARY_API_TOKEN")

jobs, err := models.DB.GetDiggerJobsForBatch(batch.ID)
var terraformOutputs = ""
for _, job := range jobs {
var jobSpec orchestrator_scheduler.JobJson
err := json.Unmarshal(job.SerializedJobSpec, &jobSpec)
if err != nil {
log.Printf("could not summarise plans due to unmarshalling error: %v", err)
return fmt.Errorf("could not summarise plans due to unmarshalling error: %v", err)
}
projectName := jobSpec.ProjectName
terraformOutputs += fmt.Sprintf("terraform output for %v \n\n", projectName) + job.TerraformOutput
}
summary, err := utils.GetAiSummaryFromTerraformPlans(terraformOutputs, summaryEndpoint, apiToken)
if err != nil {
log.Printf("could not summarise terraform outputs: %v", err)
return fmt.Errorf("could not summarise terraform outputs: %v", err)
}

if batch.AiSummaryCommentId == "" {
log.Printf("could not post summary comment, initial comment not found")
return fmt.Errorf("could not post summary comment, initial comment not found")
}

prService.EditComment(batch.PrNumber, batch.AiSummaryCommentId, summary)
}
return nil
}

func AutomergePRforBatchIfEnabled(gh utils.GithubClientProvider, batch *models.DiggerBatch) error {
diggerYmlString := batch.DiggerConfig
diggerConfigYml, err := digger_config.LoadDiggerConfigYamlFromString(diggerYmlString)
Expand All @@ -663,13 +720,6 @@ func AutomergePRforBatchIfEnabled(gh utils.GithubClientProvider, batch *models.D
automerge = false
}
if batch.Status == orchestrator_scheduler.BatchJobSucceeded && batch.BatchType == orchestrator_scheduler.DiggerCommandApply && automerge == true {
//ghService, _, err := utils.GetGithubService(
// gh,
// batch.GithubInstallationId,
// batch.RepoFullName,
// batch.RepoOwner,
// batch.RepoName,
//)
prService, err := GetPrServiceFromBatch(batch, gh)
if err != nil {
log.Printf("Error getting github service: %v", err)
Expand Down
2 changes: 2 additions & 0 deletions backend/migrations/20241229112312.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- Modify "digger_batches" table
ALTER TABLE "public"."digger_batches" ADD COLUMN "ai_summary_comment_id" text NULL, ADD COLUMN "report_terraform_outputs" boolean NULL;
3 changes: 2 additions & 1 deletion backend/migrations/atlas.sum
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
h1:+aJac+1voE00wJ5clz52DJ/fLljzr4l1KNsP8e3ZZYA=
h1:kHWmqYJMe9ZbdcztvM02SVEs5lyw/RFbKzZmqgbmSIk=
20231227132525.sql h1:43xn7XC0GoJsCnXIMczGXWis9d504FAWi4F1gViTIcw=
20240115170600.sql h1:IW8fF/8vc40+eWqP/xDK+R4K9jHJ9QBSGO6rN9LtfSA=
20240116123649.sql h1:R1JlUIgxxF6Cyob9HdtMqiKmx/BfnsctTl5rvOqssQw=
Expand Down Expand Up @@ -34,3 +34,4 @@ h1:+aJac+1voE00wJ5clz52DJ/fLljzr4l1KNsP8e3ZZYA=
20241107163722.sql h1:D5+D4TJxs80GIYrKbf70P1Vc2FUuiFVGxlu424kxYbg=
20241107172343.sql h1:E1j+7R5TZlyCKEpyYmH1mJ2zh+y5hVbtQ/PuEMJR7us=
20241114202249.sql h1:P2DhJK8MLe8gSAAz+Y5KNmsvKVw8KfLQPCncynYXEfM=
20241229112312.sql h1:Fr06uwt7LcQoLh6bjGzKB+uy9i8+uk8m6jfi+OBBbP4=
28 changes: 15 additions & 13 deletions backend/models/scheduler.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,21 @@ const DiggerVCSGithub DiggerVCSType = "github"
const DiggerVCSGitlab DiggerVCSType = "gitlab"

type DiggerBatch struct {
ID uuid.UUID `gorm:"primary_key"`
VCS DiggerVCSType
PrNumber int
CommentId *int64
Status orchestrator_scheduler.DiggerBatchStatus
BranchName string
DiggerConfig string
GithubInstallationId int64
GitlabProjectId int
RepoFullName string
RepoOwner string
RepoName string
BatchType orchestrator_scheduler.DiggerCommand
ID uuid.UUID `gorm:"primary_key"`
VCS DiggerVCSType
PrNumber int
CommentId *int64
AiSummaryCommentId string
Status orchestrator_scheduler.DiggerBatchStatus
BranchName string
DiggerConfig string
GithubInstallationId int64
GitlabProjectId int
RepoFullName string
RepoOwner string
RepoName string
BatchType orchestrator_scheduler.DiggerCommand
ReportTerraformOutputs bool
// used for module source grouping comments
SourceDetails []byte
}
Expand Down
30 changes: 16 additions & 14 deletions backend/models/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -617,22 +617,24 @@ func (db *Database) GetDiggerBatch(batchId *uuid.UUID) (*DiggerBatch, error) {
return batch, nil
}

func (db *Database) CreateDiggerBatch(vcsType DiggerVCSType, githubInstallationId int64, repoOwner string, repoName string, repoFullname string, PRNumber int, diggerConfig string, branchName string, batchType scheduler.DiggerCommand, commentId *int64, gitlabProjectId int) (*DiggerBatch, error) {
func (db *Database) CreateDiggerBatch(vcsType DiggerVCSType, githubInstallationId int64, repoOwner string, repoName string, repoFullname string, PRNumber int, diggerConfig string, branchName string, batchType scheduler.DiggerCommand, commentId *int64, gitlabProjectId int, aiSummaryCommentId string, reportTerraformOutputs bool) (*DiggerBatch, error) {
uid := uuid.New()
batch := &DiggerBatch{
ID: uid,
VCS: vcsType,
GithubInstallationId: githubInstallationId,
RepoOwner: repoOwner,
RepoName: repoName,
RepoFullName: repoFullname,
PrNumber: PRNumber,
CommentId: commentId,
Status: scheduler.BatchJobCreated,
BranchName: branchName,
DiggerConfig: diggerConfig,
BatchType: batchType,
GitlabProjectId: gitlabProjectId,
ID: uid,
VCS: vcsType,
GithubInstallationId: githubInstallationId,
RepoOwner: repoOwner,
RepoName: repoName,
RepoFullName: repoFullname,
PrNumber: PRNumber,
CommentId: commentId,
Status: scheduler.BatchJobCreated,
BranchName: branchName,
DiggerConfig: diggerConfig,
BatchType: batchType,
GitlabProjectId: gitlabProjectId,
AiSummaryCommentId: aiSummaryCommentId,
ReportTerraformOutputs: reportTerraformOutputs,
}
result := db.GormDB.Save(batch)
if result.Error != nil {
Expand Down
2 changes: 1 addition & 1 deletion backend/models/storage_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ func TestGetDiggerJobsForBatchPreloadsSummary(t *testing.T) {
resourcesUpdated := uint(2)
resourcesDeleted := uint(3)

batch, err := DB.CreateDiggerBatch(DiggerVCSGithub, 123, repoOwner, repoName, repoFullName, prNumber, diggerconfig, branchName, batchType, &commentId, 0)
batch, err := DB.CreateDiggerBatch(DiggerVCSGithub, 123, repoOwner, repoName, repoFullName, prNumber, diggerconfig, branchName, batchType, &commentId, 0, "", false)
assert.NoError(t, err)

job, err := DB.CreateDiggerJob(batch.ID, []byte(jobSpec), "workflow_file.yml")
Expand Down
5 changes: 3 additions & 2 deletions backend/services/spec.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,9 @@ func GetSpecFromJob(job models.DiggerJob) (*spec.Spec, error) {
CommentId: strconv.FormatInt(*batch.CommentId, 10),
Job: jobSpec,
Reporter: spec.ReporterSpec{
ReportingStrategy: "comments_per_run",
ReporterType: "lazy",
ReportingStrategy: "comments_per_run",
ReporterType: "lazy",
ReportTerraformOutput: batch.ReportTerraformOutputs,
},
Lock: spec.LockSpec{
LockType: "noop",
Expand Down
2 changes: 1 addition & 1 deletion backend/tasks/runs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ func TestThatRunQueueItemMovesFromQueuedToPlanningAfterPickup(t *testing.T) {

for i, testParam := range testParameters {
ciService := github2.MockCiService{}
batch, _ := models.DB.CreateDiggerBatch(models.DiggerVCSGithub, 123, "", "", "", 22, "", "", "", nil, 0)
batch, _ := models.DB.CreateDiggerBatch(models.DiggerVCSGithub, 123, "", "", "", 22, "", "", "", nil, 0, "", false)
project, _ := models.DB.CreateProject(fmt.Sprintf("test%v", i), nil, nil, false, false)
planStage, _ := models.DB.CreateDiggerRunStage(batch.ID.String())
applyStage, _ := models.DB.CreateDiggerRunStage(batch.ID.String())
Expand Down
62 changes: 62 additions & 0 deletions backend/utils/ai.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
)

Expand Down Expand Up @@ -67,3 +68,64 @@ func GenerateTerraformCode(appCode string, generationEndpoint string, apiToken s
return response.Result, nil

}

func GetAiSummaryFromTerraformPlans(plans string, summaryEndpoint string, apiToken string) (string, error) {

payload := map[string]string{
"terraform_plans": plans,
}

// Convert payload to JSON
jsonData, err := json.Marshal(payload)
if err != nil {
return "", fmt.Errorf("Error marshalling JSON: %v\n", err)
}

// Create request
req, err := http.NewRequest("POST", summaryEndpoint, bytes.NewBuffer(jsonData))
if err != nil {
return "", fmt.Errorf("Error creating request: %v\n", err)
}

// Set headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+apiToken)

// Make the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", fmt.Errorf("Error making request: %v\n", err)
}
defer resp.Body.Close()

// Read response
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("Error reading response: %v\n", err)
}

// Print response
if resp.StatusCode == 400 {
log.Printf("error while generating summary: %v", body)
return "", fmt.Errorf("unable to generate summary")
}

if resp.StatusCode != 200 {
return "", fmt.Errorf("unexpected error occured while generating code")
}

type GeneratorResponse struct {
Result string `json:"result"`
Status string `json:"status"`
}

var response GeneratorResponse
err = json.Unmarshal(body, &response)
if err != nil {
return "", fmt.Errorf("unable to parse generator response: %v", err)
}

return response.Result, nil

}
Loading
Loading