Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
13 changes: 13 additions & 0 deletions plugin.json
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,19 @@
"type": "bool",
"help_text": "When set to 'true' you will get a notification with less details when a draft pull request is created and a notification with complete details when they are marked as ready for review. When set to 'false' no notifications are delivered for draft pull requests.",
"default": false
},
{
"key": "ReviewTargetDays",
"display_name": "PR review target (days):",
"type": "number",
"default": "0",
"help_text": "Optional. Number of calendar days until a review counts as due. The start time is when you were requested as a reviewer (recorded from GitHub pull_request review_requested webhooks to this server); if unknown, the PR open date is used. When greater than zero, /github todo shows due/overdue text and the sidebar review counter can be color-coded. Set to 0 to disable."
},
{
"key": "OverdueReviewsChannelID",
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This is probably fine for a first iteration of this feature, but I'm wondering if we'd want to introduce a slash command to make this a bit more configurable.

I feel like in real use-cases, organizations might want to be able to configure these digests into each channel with a list of repositories that might be most relevant for the members of that channel

"display_name": "Post overdue review alerts to channel (ID):",
"type": "text",
"help_text": "Optional. Paste a channel ID (Channel menu > View Info). When set together with PR review target (days), the plugin posts one aggregated overdue-review digest to this channel each day shortly after midnight in the server local timezone (the GitHub bot must be a member of the channel)."
}
],
"footer": "* To report an issue, make a suggestion or a contribution, [check the repository](https://github.com/mattermost/mattermost-plugin-github)."
Expand Down
2 changes: 2 additions & 0 deletions server/plugin/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -1054,6 +1054,8 @@ func (p *Plugin) getSidebarData(c *UserContext) (*SidebarContent, error) {
return nil, err
}

p.enrichReviewsWithSLAStart(reviewResp, c.GHInfo.GitHubUsername)

return &SidebarContent{
PRs: openPRResp,
Assignments: assignmentResp,
Expand Down
9 changes: 9 additions & 0 deletions server/plugin/configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ type Configuration struct {
UsePreregisteredApplication bool `json:"usepreregisteredapplication"`
ShowAuthorInCommitNotification bool `json:"showauthorincommitnotification"`
GetNotificationForDraftPRs bool `json:"getnotificationfordraftprs"`
// ReviewTargetDays is the number of calendar days from PR open until a review is "due" (0 = SLA disabled).
ReviewTargetDays int `json:"reviewtargetdays"`
// OverdueReviewsChannelID is an optional channel ID for daily alerts when users have overdue review requests.
OverdueReviewsChannelID string `json:"overduereviewschannelid"`
}

func (c *Configuration) ToMap() (map[string]any, error) {
Expand Down Expand Up @@ -100,6 +104,10 @@ func (c *Configuration) getBaseURL() string {
func (c *Configuration) sanitize() {
c.EnterpriseBaseURL = strings.TrimRight(c.EnterpriseBaseURL, "/")
c.EnterpriseUploadURL = strings.TrimRight(c.EnterpriseUploadURL, "/")
c.OverdueReviewsChannelID = strings.TrimSpace(c.OverdueReviewsChannelID)
if c.ReviewTargetDays < 0 {
c.ReviewTargetDays = 0
}

// Trim spaces around org and OAuth credentials
c.GitHubOrg = strings.TrimSpace(c.GitHubOrg)
Expand All @@ -120,6 +128,7 @@ func (c *Configuration) IsSASS() bool {
func (c *Configuration) ClientConfiguration() map[string]any {
return map[string]any{
"left_sidebar_enabled": c.EnableLeftSidebar,
"review_target_days": c.ReviewTargetDays,
}
}

Expand Down
2 changes: 2 additions & 0 deletions server/plugin/graphql/lhs_request.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ type GithubPRDetails struct {
Additions *githubv4.Int `json:"additions,omitempty"`
Deletions *githubv4.Int `json:"deletions,omitempty"`
ChangedFiles *githubv4.Int `json:"changed_files,omitempty"`
// ReviewSLAStartAt is RFC3339 UTC time used for SLA when the plugin knows review request time (webhook); clients may fall back to created_at.
ReviewSLAStartAt *string `json:"review_sla_start,omitempty"`
}

func (c *Client) GetLHSData(ctx context.Context) ([]*GithubPRDetails, []*github.Issue, []*GithubPRDetails, error) {
Expand Down
21 changes: 20 additions & 1 deletion server/plugin/plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"slices"
"strings"
"sync"
"time"

"github.com/google/go-github/v54/github"
"github.com/gorilla/mux"
Expand Down Expand Up @@ -103,6 +104,8 @@ type Plugin struct {
webhookBroker *WebhookBroker
oauthBroker *OAuthBroker

slaDigestCancel context.CancelFunc

emojiMap map[string]string
}

Expand Down Expand Up @@ -296,10 +299,18 @@ func (p *Plugin) OnActivate() error {
p.client.Log.Debug("failed to reset user tokens", "error", resetErr.Error())
}
}()

ctx, cancel := context.WithCancel(context.Background())
p.slaDigestCancel = cancel
go p.runSLADigestScheduler(ctx)

return nil
}

func (p *Plugin) OnDeactivate() error {
if p.slaDigestCancel != nil {
p.slaDigestCancel()
}
p.webhookBroker.Close()
p.oauthBroker.Close()
return nil
Expand Down Expand Up @@ -944,13 +955,21 @@ func (p *Plugin) GetToDo(ctx context.Context, info *GitHubUserInfo, githubClient

text.WriteString("##### Review Requests\n")

targetDays := config.ReviewTargetDays
now := time.Now()

if issueResults.GetTotal() == 0 {
text.WriteString("You don't have any pull requests awaiting your review.\n")
} else {
fmt.Fprintf(&text, "You have %v pull requests awaiting your review:\n", issueResults.GetTotal())

for _, pr := range issueResults.Issues {
text.WriteString(getToDoDisplayText(baseURL, pr.GetTitle(), pr.GetHTMLURL(), "", nil))
line := strings.TrimSuffix(getToDoDisplayText(baseURL, pr.GetTitle(), pr.GetHTMLURL(), "", nil), "\n")
slaStart := p.effectiveReviewSLAStart(pr, baseURL, info.GitHubUsername)
if suffix, _ := reviewSLAMarkdown(slaStart, targetDays, now); suffix != "" {
line += suffix
}
text.WriteString(line + "\n")
}
}

Expand Down
136 changes: 136 additions & 0 deletions server/plugin/review_sla.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
// Copyright (c) 2018-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.

package plugin

import (
"crypto/sha256"
"encoding/hex"
"strconv"
"strings"
"time"

"github.com/google/go-github/v54/github"

"github.com/mattermost/mattermost-plugin-github/server/plugin/graphql"
)

const slaReviewReqKeyPrefix = "slarr_v1_"

// reviewSLAStartKey returns a stable KV key for (repo, PR, requested reviewer login).
func reviewSLAStartKey(owner, repo string, prNumber int, githubLogin string) string {
normalized := strings.ToLower(strings.TrimSpace(owner)) + "/" + strings.ToLower(strings.TrimSpace(repo)) +
"#" + strconv.Itoa(prNumber) + "@" + strings.ToLower(strings.TrimSpace(githubLogin))
sum := sha256.Sum256([]byte(normalized))
return slaReviewReqKeyPrefix + hex.EncodeToString(sum[:16])
}

// recordReviewRequestSLAStart stores when a reviewer was requested (from pull_request / review_requested webhook).
// Each new request overwrites the previous time for that (repo, PR, reviewer) pair so the SLA clock restarts on re-request.
func (p *Plugin) recordReviewRequestSLAStart(event *github.PullRequestEvent, requestedGitHubLogin string) {
if event.GetRepo() == nil || event.GetPullRequest() == nil {
return
}
owner := event.GetRepo().GetOwner().GetLogin()
repo := event.GetRepo().GetName()
num := event.GetPullRequest().GetNumber()
if owner == "" || repo == "" || num == 0 || requestedGitHubLogin == "" {
return
}
key := reviewSLAStartKey(owner, repo, num, requestedGitHubLogin)
at := time.Now().UTC()
val := []byte(at.Format(time.RFC3339Nano))
if _, err := p.store.Set(key, val); err != nil {
p.client.Log.Warn("Failed to store review SLA start time", "key", key, "error", err.Error())
}
}

// cleanupReviewSLAKeys deletes all stored SLA start-time keys for a closed/merged PR.
func (p *Plugin) cleanupReviewSLAKeys(event *github.PullRequestEvent) {
if event.GetRepo() == nil || event.GetPullRequest() == nil {
return
}
owner := event.GetRepo().GetOwner().GetLogin()
repo := event.GetRepo().GetName()
num := event.GetPullRequest().GetNumber()
if owner == "" || repo == "" || num == 0 {
return
}
for _, reviewer := range event.GetPullRequest().RequestedReviewers {
login := reviewer.GetLogin()
if login == "" {
continue
}
key := reviewSLAStartKey(owner, repo, num, login)
if err := p.store.Delete(key); err != nil {
p.client.Log.Debug("Failed to delete SLA key on PR close", "key", key, "error", err.Error())
}
}
}

func (p *Plugin) getReviewSLAStartTime(owner, repo string, prNumber int, githubLogin string) time.Time {
key := reviewSLAStartKey(owner, repo, prNumber, githubLogin)
var raw []byte
if err := p.store.Get(key, &raw); err != nil {
return time.Time{}
}
if len(raw) == 0 {
return time.Time{}
}
t, err := time.Parse(time.RFC3339Nano, string(raw))
if err != nil {
t, err = time.Parse(time.RFC3339, string(raw))
}
if err != nil {
return time.Time{}
}
return t.UTC()
}

// issueOwnerRepo resolves owner/name for a search result issue (prefers API fields, else HTML URL).
func issueOwnerRepo(pr *github.Issue, baseURL string) (owner, repo string) {
if pr.Repository != nil {
if o := pr.GetRepository().GetOwner(); o != nil {
owner = o.GetLogin()
}
repo = pr.GetRepository().GetName()
}
if owner != "" && repo != "" {
return owner, repo
}
return parseOwnerAndRepo(pr.GetHTMLURL(), baseURL)
}

// effectiveReviewSLAStart returns the timestamp used for SLA: when we recorded a review_request webhook
// for this reviewer on this PR, else the PR created time.
func (p *Plugin) effectiveReviewSLAStart(pr *github.Issue, baseURL, reviewerGitHubLogin string) github.Timestamp {
owner, repo := issueOwnerRepo(pr, baseURL)
num := pr.GetNumber()
if owner == "" || repo == "" || num == 0 {
return pr.GetCreatedAt()
}
if t := p.getReviewSLAStartTime(owner, repo, num, reviewerGitHubLogin); !t.IsZero() {
return github.Timestamp{Time: t}
}
return pr.GetCreatedAt()
}

// enrichReviewsWithSLAStart sets review_sla_start on LHS review items so the webapp can match server SLA logic.
func (p *Plugin) enrichReviewsWithSLAStart(reviews []*graphql.GithubPRDetails, reviewerLogin string) {
cfg := p.getConfiguration()
if cfg.ReviewTargetDays <= 0 {
return
}
baseURL := cfg.getBaseURL()
for _, d := range reviews {
if d == nil || d.Issue == nil {
continue
}
eff := p.effectiveReviewSLAStart(d.Issue, baseURL, reviewerLogin)
if eff.IsZero() {
continue
}
s := eff.Time.UTC().Format(time.RFC3339)
d.ReviewSLAStartAt = &s
}
}
19 changes: 19 additions & 0 deletions server/plugin/review_sla_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Copyright (c) 2018-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.

package plugin

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestReviewSLAStartKeyStable(t *testing.T) {
k1 := reviewSLAStartKey("Mattermost", "mattermost", 12345, "octocat")
k2 := reviewSLAStartKey("mattermost", "mattermost", 12345, "OctoCat")
assert.Equal(t, k1, k2, "key should be case-insensitive")

k3 := reviewSLAStartKey("Mattermost", "mattermost", 99999, "octocat")
assert.NotEqual(t, k1, k3)
}
Loading
Loading