Skip to content

Commit c2ea290

Browse files
authored
segment (#2304)
* segment
1 parent fdb6e88 commit c2ea290

File tree

20 files changed

+146
-59
lines changed

20 files changed

+146
-59
lines changed

backend/controllers/github_callback.go

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,17 @@ package controllers
22

33
import (
44
"fmt"
5+
"log/slog"
6+
"net/http"
7+
"strconv"
8+
"strings"
9+
510
"github.com/diggerhq/digger/backend/models"
11+
"github.com/diggerhq/digger/backend/segment"
612
"github.com/diggerhq/digger/backend/utils"
713
"github.com/diggerhq/digger/libs/ci/github"
814
"github.com/gin-gonic/gin"
915
"github.com/google/uuid"
10-
"log/slog"
11-
"net/http"
12-
"strconv"
13-
"strings"
1416
)
1517

1618
func (d DiggerController) GithubAppCallbackPage(c *gin.Context) {
@@ -111,7 +113,7 @@ func (d DiggerController) GithubAppCallbackPage(c *gin.Context) {
111113
"externalId", externalId,
112114
)
113115

114-
org, err := models.DB.CreateOrganisation(name, "digger", externalId)
116+
org, err := models.DB.CreateOrganisation(name, "digger", externalId, nil)
115117
if err != nil {
116118
slog.Error("Error creating organization",
117119
"name", name,
@@ -151,6 +153,13 @@ func (d DiggerController) GithubAppCallbackPage(c *gin.Context) {
151153
org := link.Organisation
152154
orgId := link.OrganisationId
153155

156+
var vcsOwner string = ""
157+
if installation.Account.Login != nil {
158+
vcsOwner = *installation.Account.Login
159+
}
160+
// we have multiple repos here, we don't really want to send an track event for each repo, so we just send the vcs owner
161+
segment.Track(*org, vcsOwner, "", "github", "vcs_repo_installed", map[string]string{})
162+
154163
// create a github installation link (org ID matched to installation ID)
155164
_, err = models.DB.CreateGithubInstallationLink(org, installationId64)
156165
if err != nil {

backend/controllers/github_comment.go

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,12 @@ package controllers
33
import (
44
"encoding/json"
55
"fmt"
6+
"log/slog"
7+
"os"
8+
"runtime/debug"
9+
"strconv"
10+
"strings"
11+
612
"github.com/diggerhq/digger/backend/ci_backends"
713
config2 "github.com/diggerhq/digger/backend/config"
814
locking2 "github.com/diggerhq/digger/backend/locking"
@@ -18,11 +24,6 @@ import (
1824
"github.com/diggerhq/digger/libs/scheduler"
1925
"github.com/google/go-github/v61/github"
2026
"github.com/samber/lo"
21-
"log/slog"
22-
"os"
23-
"runtime/debug"
24-
"strconv"
25-
"strings"
2627
)
2728

2829
func handleIssueCommentEvent(gh utils.GithubClientProvider, payload *github.IssueCommentEvent, ciBackendProvider ci_backends.CiBackendProvider, appId int64, postCommentHooks []IssueCommentHook) error {
@@ -55,6 +56,12 @@ func handleIssueCommentEvent(gh utils.GithubClientProvider, payload *github.Issu
5556
isDraft := payload.Issue.GetDraft()
5657
userCommentId := *payload.GetComment().ID
5758
actor := *payload.Sender.Login
59+
var vcsActorID string = ""
60+
if payload.Sender != nil && payload.Sender.Email != nil {
61+
vcsActorID = *payload.Sender.Email
62+
} else if payload.Sender != nil && payload.Sender.Login != nil {
63+
vcsActorID = *payload.Sender.Login
64+
}
5865
commentBody := *payload.Comment.Body
5966
defaultBranch := *payload.Repo.DefaultBranch
6067
isPullRequest := payload.Issue.IsPullRequest()
@@ -145,6 +152,15 @@ func handleIssueCommentEvent(gh utils.GithubClientProvider, payload *github.Issu
145152
"orgId", orgId,
146153
)
147154

155+
org, err := models.DB.GetOrganisationById(orgId)
156+
if err != nil || org == nil {
157+
slog.Error("Error getting organisation",
158+
"orgId", orgId,
159+
"error", err)
160+
commentReporterManager.UpdateComment(fmt.Sprintf(":x: Failed to get organisation by ID"))
161+
return fmt.Errorf("error getting organisation")
162+
}
163+
148164
diggerYmlStr, ghService, config, projectsGraph, prSourceBranch, commitSha, changedFiles, err := getDiggerConfigForPR(gh, orgId, prLabelsStr, installationId, repoFullName, repoOwner, repoName, cloneURL, issueNumber)
149165
if err != nil {
150166
slog.Error("Error getting Digger config for PR",
@@ -445,6 +461,9 @@ func handleIssueCommentEvent(gh utils.GithubClientProvider, payload *github.Issu
445461
return nil
446462
}
447463

464+
// If we reach here then we have created a comment that would have led to more events
465+
segment.Track(*org, repoOwner, vcsActorID, "github", "issue_digger_comment", map[string]string{"comment": commentBody})
466+
448467
err = utils.SetPRStatusForJobs(ghService, issueNumber, jobs)
449468
if err != nil {
450469
slog.Error("Error setting status for PR",
@@ -583,12 +602,9 @@ func handleIssueCommentEvent(gh utils.GithubClientProvider, payload *github.Issu
583602
commentReporterManager.UpdateComment(fmt.Sprintf(":x: UpdateDiggerBatch error: %v", err))
584603
return fmt.Errorf("error updating digger batch")
585604
}
586-
587605
slog.Debug("Successfully updated batch with source details", "batchId", batchId)
588606
}
589607

590-
segment.Track(strconv.Itoa(int(orgId)), "backend_trigger_job")
591-
592608
slog.Info("Getting CI backend",
593609
"issueNumber", issueNumber,
594610
"repoFullName", repoFullName,
@@ -614,6 +630,10 @@ func handleIssueCommentEvent(gh utils.GithubClientProvider, payload *github.Issu
614630
return fmt.Errorf("error fetching ci backed %v", err)
615631
}
616632

633+
segment.Track(*org, repoOwner, vcsActorID, "github", "backend_trigger_job", map[string]string{
634+
"comment": commentBody,
635+
})
636+
617637
slog.Info("Triggering Digger jobs",
618638
"issueNumber", issueNumber,
619639
"batchId", batchId,

backend/controllers/github_pull_request.go

Lines changed: 34 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,13 @@ package controllers
33
import (
44
"encoding/json"
55
"fmt"
6+
"log/slog"
7+
"os"
8+
"runtime/debug"
9+
"slices"
10+
"strconv"
11+
"time"
12+
613
"github.com/diggerhq/digger/backend/ci_backends"
714
config2 "github.com/diggerhq/digger/backend/config"
815
locking2 "github.com/diggerhq/digger/backend/locking"
@@ -16,12 +23,6 @@ import (
1623
"github.com/diggerhq/digger/libs/scheduler"
1724
"github.com/google/go-github/v61/github"
1825
"github.com/samber/lo"
19-
"log/slog"
20-
"os"
21-
"runtime/debug"
22-
"slices"
23-
"strconv"
24-
"time"
2526
)
2627

2728
func handlePullRequestEvent(gh utils.GithubClientProvider, payload *github.PullRequestEvent, ciBackendProvider ci_backends.CiBackendProvider, appId int64) error {
@@ -49,6 +50,12 @@ func handlePullRequestEvent(gh utils.GithubClientProvider, payload *github.PullR
4950
branch := payload.PullRequest.Head.GetRef()
5051
action := *payload.Action
5152
labels := payload.PullRequest.Labels
53+
var vcsActorId string = ""
54+
if payload.Sender != nil && payload.Sender.Email != nil {
55+
vcsActorId = *payload.Sender.Email
56+
} else if payload.Sender != nil && payload.Sender.Login != nil {
57+
vcsActorId = *payload.Sender.Login
58+
}
5259
prLabelsStr := lo.Map(labels, func(label *github.Label, i int) string {
5360
return *label.Name
5461
})
@@ -141,6 +148,15 @@ func handlePullRequestEvent(gh utils.GithubClientProvider, payload *github.PullR
141148
}
142149
}
143150

151+
org, err := models.DB.GetOrganisationById(organisationId)
152+
if err != nil || org == nil {
153+
slog.Error("Error getting organisation",
154+
"orgId", organisationId,
155+
"error", err)
156+
commentReporterManager.UpdateComment(fmt.Sprintf(":x: Failed to get organisation by ID"))
157+
return fmt.Errorf("error getting organisation")
158+
}
159+
144160
diggerYmlStr, ghService, config, projectsGraph, _, _, changedFiles, err := getDiggerConfigForPR(gh, organisationId, prLabelsStr, installationId, repoFullName, repoOwner, repoName, cloneURL, prNumber)
145161
if err != nil {
146162
slog.Error("Error getting Digger config for PR",
@@ -244,6 +260,7 @@ func handlePullRequestEvent(gh utils.GithubClientProvider, payload *github.PullR
244260
"commands", jobsForImpactedProjects[0].Commands,
245261
"error", err,
246262
)
263+
segment.Track(*org, repoOwner, vcsActorId, "github", "pull_request_ERROR", map[string]string{"error": err.Error()})
247264
commentReporterManager.UpdateComment(fmt.Sprintf(":x: could not determine digger command from job: %v", err))
248265
return fmt.Errorf("unknown digger command in comment %v", err)
249266
}
@@ -340,12 +357,16 @@ func handlePullRequestEvent(gh utils.GithubClientProvider, payload *github.PullR
340357
return nil
341358
}
342359

360+
// a pull request has led to jobs which would be triggered (ignoring closed event by here)
361+
segment.Track(*org, repoOwner, vcsActorId, "github", "pull_request", map[string]string{})
362+
343363
commentReporter, err := commentReporterManager.UpdateComment(":construction_worker: Digger starting... Config loaded successfully")
344364
if err != nil {
345365
slog.Error("Error initializing comment reporter",
346366
"prNumber", prNumber,
347367
"error", err,
348368
)
369+
segment.Track(*org, repoOwner, vcsActorId, "github", "pull_request_ERROR", map[string]string{"error": err.Error()})
349370
return fmt.Errorf("error initializing comment reporter")
350371
}
351372

@@ -355,6 +376,7 @@ func handlePullRequestEvent(gh utils.GithubClientProvider, payload *github.PullR
355376
"prNumber", prNumber,
356377
"error", err,
357378
)
379+
segment.Track(*org, repoOwner, vcsActorId, "github", "pull_request_ERROR", map[string]string{"error": err.Error()})
358380
commentReporterManager.UpdateComment(fmt.Sprintf(":x: error setting status for PR: %v", err))
359381
return fmt.Errorf("error setting status for PR: %v", err)
360382
}
@@ -415,6 +437,7 @@ func handlePullRequestEvent(gh utils.GithubClientProvider, payload *github.PullR
415437
"commentId", commentReporter.CommentId,
416438
"error", err,
417439
)
440+
segment.Track(*org, repoOwner, vcsActorId, "github", "pull_request_ERROR", map[string]string{"error": err.Error()})
418441
commentReporterManager.UpdateComment(fmt.Sprintf(":x: could not handle commentId: %v", err))
419442
}
420443

@@ -427,6 +450,7 @@ func handlePullRequestEvent(gh utils.GithubClientProvider, payload *github.PullR
427450
"prNumber", prNumber,
428451
"error", err,
429452
)
453+
segment.Track(*org, repoOwner, vcsActorId, "github", "pull_request_ERROR", map[string]string{"error": err.Error()})
430454
commentReporterManager.UpdateComment(fmt.Sprintf(":x: could not post ai comment summary comment id: %v", err))
431455
return fmt.Errorf("could not post ai summary comment: %v", err)
432456
}
@@ -470,6 +494,7 @@ func handlePullRequestEvent(gh utils.GithubClientProvider, payload *github.PullR
470494
"prNumber", prNumber,
471495
"error", err,
472496
)
497+
segment.Track(*org, repoOwner, vcsActorId, "github", "pull_request_ERROR", map[string]string{"error": err.Error()})
473498
commentReporterManager.UpdateComment(fmt.Sprintf(":x: ConvertJobsToDiggerJobs error: %v", err))
474499
return fmt.Errorf("error converting jobs")
475500
}
@@ -525,7 +550,7 @@ func handlePullRequestEvent(gh utils.GithubClientProvider, payload *github.PullR
525550
slog.Debug("Successfully updated batch with source details", "batchId", batchId)
526551
}
527552

528-
segment.Track(strconv.Itoa(int(organisationId)), "backend_trigger_job")
553+
segment.Track(*org, repoOwner, vcsActorId, "github", "backend_trigger_job", map[string]string{})
529554

530555
slog.Info("Getting CI backend",
531556
"prNumber", prNumber,
@@ -548,6 +573,7 @@ func handlePullRequestEvent(gh utils.GithubClientProvider, payload *github.PullR
548573
"repoFullName", repoFullName,
549574
"error", err,
550575
)
576+
segment.Track(*org, repoOwner, vcsActorId, "github", "pull_request_ERROR", map[string]string{"error": err.Error()})
551577
commentReporterManager.UpdateComment(fmt.Sprintf(":x: GetCiBackend error: %v", err))
552578
return fmt.Errorf("error fetching ci backed %v", err)
553579
}
@@ -565,6 +591,7 @@ func handlePullRequestEvent(gh utils.GithubClientProvider, payload *github.PullR
565591
"batchId", batchId,
566592
"error", err,
567593
)
594+
segment.Track(*org, repoOwner, vcsActorId, "github", "pull_request_ERROR", map[string]string{"error": err.Error()})
568595
commentReporterManager.UpdateComment(fmt.Sprintf(":x: TriggerDiggerJobs error: %v", err))
569596
return fmt.Errorf("error triggering Digger Jobs")
570597
}

backend/controllers/github_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -600,7 +600,7 @@ func setupSuite(tb testing.TB) (func(tb testing.TB), *models.Database) {
600600
orgTenantId := "11111111-1111-1111-1111-111111111111"
601601
externalSource := "test"
602602
orgName := "testOrg"
603-
org, err := database.CreateOrganisation(orgName, externalSource, orgTenantId)
603+
org, err := database.CreateOrganisation(orgName, externalSource, orgTenantId, nil)
604604
if err != nil {
605605
panic(err)
606606
}

backend/controllers/internal_users.go

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,16 @@ import (
55
"net/http"
66

77
"github.com/diggerhq/digger/backend/models"
8+
"github.com/diggerhq/digger/backend/segment"
89
"github.com/gin-gonic/gin"
910
)
1011

1112
func (d DiggerController) UpsertOrgInternal(c *gin.Context) {
1213
type OrgCreateRequest struct {
13-
Name string `json:"org_name"`
14-
ExternalSource string `json:"external_source"`
15-
ExternalId string `json:"external_id"`
14+
Name string `json:"org_name"`
15+
ExternalSource string `json:"external_source"`
16+
ExternalId string `json:"external_id"`
17+
AdminEmail *string `json:"admin_email,omitempty"`
1618
}
1719

1820
var request OrgCreateRequest
@@ -26,6 +28,7 @@ func (d DiggerController) UpsertOrgInternal(c *gin.Context) {
2628
name := request.Name
2729
externalSource := request.ExternalSource
2830
externalId := request.ExternalId
31+
adminEmail := request.AdminEmail
2932

3033
slog.Info("Creating or updating organization",
3134
"name", name,
@@ -42,13 +45,12 @@ func (d DiggerController) UpsertOrgInternal(c *gin.Context) {
4245

4346
if org == nil {
4447
slog.Info("Organization not found, creating new one", "externalId", externalId)
45-
org, err = models.DB.CreateOrganisation(name, externalSource, externalId)
46-
}
47-
48-
if err != nil {
49-
slog.Error("Error creating org", "name", name, "externalId", externalId, "error", err)
50-
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error creating org"})
51-
return
48+
org, err = models.DB.CreateOrganisation(name, externalSource, externalId, adminEmail)
49+
if err != nil {
50+
slog.Error("Error creating org", "name", name, "externalId", externalId, "error", err)
51+
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error creating org"})
52+
return
53+
}
5254
}
5355

5456
slog.Info("Successfully upserted organization", "orgId", org.ID, "externalId", externalId)
@@ -102,6 +104,8 @@ func (d DiggerController) CreateUserInternal(c *gin.Context) {
102104
return
103105
}
104106

107+
segment.IdentifyClient(userEmail, userEmail, userEmail, userEmail, org.Name, org.ExternalId, string(org.BillingPlan))
108+
105109
slog.Info("Successfully created user", "userId", user.ID, "email", userEmail, "orgId", org.ID)
106110
c.JSON(http.StatusOK, gin.H{"status": "success", "user_id": user.ID})
107111
}

backend/controllers/orgs.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,7 @@ func AssociateTenantIdToDiggerOrg(c *gin.Context) {
184184
}
185185

186186
if org == nil {
187-
newOrg, err := models.DB.CreateOrganisation(nameStr, "", tenantIdStr)
187+
newOrg, err := models.DB.CreateOrganisation(nameStr, "", tenantIdStr, nil)
188188
if err != nil {
189189
slog.Error("Failed to create organisation", "tenantId", tenantIdStr, "name", nameStr, "error", err)
190190
c.AbortWithStatus(http.StatusInternalServerError)

backend/controllers/projects.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import (
1616
"github.com/diggerhq/digger/backend/logging"
1717
"github.com/diggerhq/digger/backend/middleware"
1818
"github.com/diggerhq/digger/backend/models"
19+
"github.com/diggerhq/digger/backend/segment"
1920
"github.com/diggerhq/digger/backend/services"
2021
"github.com/diggerhq/digger/backend/utils"
2122
"github.com/diggerhq/digger/libs/comment_utils/reporting"
@@ -655,6 +656,13 @@ func (d DiggerController) SetJobStatusForProject(c *gin.Context) {
655656

656657
batchId := *job.BatchID
657658

659+
org, err := models.DB.GetOrganisationById(orgId)
660+
if err != nil || org == nil {
661+
slog.Error("Error getting organisation", "jobId", jobId, "error", err)
662+
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error fetching organisation"})
663+
return
664+
}
665+
658666
slog.Info("Processing job status update",
659667
"jobId", jobId,
660668
"currentStatus", job.Status,
@@ -732,6 +740,8 @@ func (d DiggerController) SetJobStatusForProject(c *gin.Context) {
732740
}(c.Request.Context())
733741

734742
case "succeeded":
743+
batch := job.Batch
744+
segment.Track(*org, "", "", "github", "ci_job_successful", map[string]string{"ci_job_type": string(batch.BatchType)})
735745
job.Status = orchestrator_scheduler.DiggerJobSucceeded
736746
job.TerraformOutput = request.TerraformOutput
737747
if request.Footprint != nil {
@@ -896,6 +906,7 @@ func (d DiggerController) SetJobStatusForProject(c *gin.Context) {
896906
}(c.Request.Context())
897907

898908
case "failed":
909+
segment.Track(*org, "", "", "github", "ci_job_failed", nil)
899910
job.Status = orchestrator_scheduler.DiggerJobFailed
900911
job.TerraformOutput = request.TerraformOutput
901912
err := models.DB.UpdateDiggerJob(job)

backend/go.sum

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -750,6 +750,8 @@ github.com/ajstarks/deck v0.0.0-20200831202436-30c9fc6549a9/go.mod h1:JynElWSGnm
750750
github.com/ajstarks/deck/generate v0.0.0-20210309230005-c3f852c02e19/go.mod h1:T13YZdzov6OU0A1+RfKZiZN9ca6VeKdBdyDV+BY97Tk=
751751
github.com/ajstarks/svgo v0.0.0-20180226025133-644b8db467af/go.mod h1:K08gAheRH3/J6wwsYMMT4xOr94bZjxIelGM0+d/wbFw=
752752
github.com/ajstarks/svgo v0.0.0-20211024235047-1546f124cd8b/go.mod h1:1KcenG0jGWcpt8ov532z81sp/kMMUG485J2InIOyADM=
753+
github.com/alecthomas/kong v0.7.1 h1:azoTh0IOfwlAX3qN9sHWTxACE2oV8Bg2gAwBsMwDQY4=
754+
github.com/alecthomas/kong v0.7.1/go.mod h1:n1iCIO2xS46oE8ZfYCNDqdR0b0wZNrXAIAqro/2132U=
753755
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
754756
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
755757
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=

0 commit comments

Comments
 (0)