Skip to content

Commit 386e7f8

Browse files
christopher-beschEarl Warren
authored and
Earl Warren
committed
send mail on failed or recovered workflow run (go-gitea#7509)
Send a Mail when an action run fails or a workflow recovers. This PR depends on https://codeberg.org/forgejo/forgejo/pulls/7491 closes go-gitea#3719 ## Checklist The [contributor guide](https://forgejo.org/docs/next/contributor/) contains information that will be helpful to first time contributors. There also are a few [conditions for merging Pull Requests in Forgejo repositories](https://codeberg.org/forgejo/governance/src/branch/main/PullRequestsAgreement.md). You are also welcome to join the [Forgejo development chatroom](https://matrix.to/#/#forgejo-development:matrix.org). ### Tests - I added test coverage for Go changes... - [x] in their respective `*_test.go` for unit tests. - [ ] in the `tests/integration` directory if it involves interactions with a live Forgejo server. - I added test coverage for JavaScript changes... - [ ] in `web_src/js/*.test.js` if it can be unit tested. - [ ] in `tests/e2e/*.test.e2e.js` if it requires interactions with a live Forgejo server (see also the [developer guide for JavaScript testing](https://codeberg.org/forgejo/forgejo/src/branch/forgejo/tests/e2e/README.md#end-to-end-tests)). ### Documentation - [ ] I created a pull request [to the documentation](https://codeberg.org/forgejo/docs) to explain to Forgejo users how to use this change. - [x] I did not document these changes and I do not expect someone else to do it. ### Release notes - [ ] I do not want this change to show in the release notes. - [x] I want the title to show in the release notes with a link to this pull request. - [ ] I want the content of the `release-notes/<pull request number>.md` to be be used for the release notes instead of the title. <!--start release-notes-assistant--> ## Release notes <!--URL:https://codeberg.org/forgejo/forgejo--> - Features - [PR](https://codeberg.org/forgejo/forgejo/pulls/7509): <!--number 7509 --><!--line 0 --><!--description c2VuZCBtYWlsIG9uIGZhaWxlZCBvciByZWNvdmVyZWQgd29ya2Zsb3cgcnVu-->send mail on failed or recovered workflow run<!--description--> <!--end release-notes-assistant--> Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/7509 Reviewed-by: Earl Warren <[email protected]> Co-authored-by: christopher-besch <[email protected]> Co-committed-by: christopher-besch <[email protected]>
1 parent bc99bf5 commit 386e7f8

File tree

7 files changed

+298
-10
lines changed

7 files changed

+298
-10
lines changed

options/locale_next/locale_en-US.json

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,5 +21,13 @@
2121
"alert.asset_load_failed": "Failed to load asset files from {path}. Please make sure the asset files can be accessed.",
2222
"alert.range_error": " must be a number between %[1]s and %[2]s.",
2323
"install.invalid_lfs_path": "Unable to create the LFS root at the specified path: %[1]s",
24+
"mail.actions.successful_run_after_failure_subject": "Workflow %[1]s recovered in repository %[2]s",
25+
"mail.actions.not_successful_run_subject": "Workflow %[1]s failed in repository %[2]s",
26+
"mail.actions.successful_run_after_failure": "Workflow %[1]s recovered in repository %[2]s",
27+
"mail.actions.not_successful_run": "Workflow %[1]s failed in repository %[2]s",
28+
"mail.actions.run_info_cur_status": "This Run's Status: %[1]s (just updated from %[2]s)",
29+
"mail.actions.run_info_previous_status": "Previous Run's Status: %[1]s",
30+
"mail.actions.run_info_ref": "Branch: %[1]s (%[2]s)",
31+
"mail.actions.run_info_trigger": "Triggered because: %[1]s by: %[2]s",
2432
"meta.last_line": "Thank you for translating Forgejo! This line isn't seen by the users but it serves other purposes in the translation management. You can place a fun fact in the translation instead of translating it."
2533
}

services/mailer/mail_actions.go

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
// Copyright 2025 The Forgejo Authors. All rights reserved.
2+
// SPDX-License-Identifier: GPL-3.0-or-later
3+
package mailer
4+
5+
import (
6+
"bytes"
7+
8+
actions_model "forgejo.org/models/actions"
9+
user_model "forgejo.org/models/user"
10+
"forgejo.org/modules/base"
11+
"forgejo.org/modules/setting"
12+
"forgejo.org/modules/translation"
13+
)
14+
15+
const (
16+
tplActionNowDone base.TplName = "actions/now_done"
17+
)
18+
19+
// requires !run.Status.IsSuccess() or !lastRun.Status.IsSuccess()
20+
func MailActionRun(run *actions_model.ActionRun, priorStatus actions_model.Status, lastRun *actions_model.ActionRun) error {
21+
if setting.MailService == nil {
22+
// No mail service configured
23+
return nil
24+
}
25+
26+
if run.TriggerUser.Email != "" && run.TriggerUser.EmailNotificationsPreference != user_model.EmailNotificationsDisabled {
27+
if err := sendMailActionRun(run.TriggerUser, run, priorStatus, lastRun); err != nil {
28+
return err
29+
}
30+
}
31+
32+
if run.Repo.Owner.Email != "" && run.Repo.Owner.Email != run.TriggerUser.Email && run.Repo.Owner.EmailNotificationsPreference != user_model.EmailNotificationsDisabled {
33+
if err := sendMailActionRun(run.Repo.Owner, run, priorStatus, lastRun); err != nil {
34+
return err
35+
}
36+
}
37+
38+
return nil
39+
}
40+
41+
func sendMailActionRun(to *user_model.User, run *actions_model.ActionRun, priorStatus actions_model.Status, lastRun *actions_model.ActionRun) error {
42+
var (
43+
locale = translation.NewLocale(to.Language)
44+
content bytes.Buffer
45+
)
46+
47+
var subject string
48+
if run.Status.IsSuccess() {
49+
subject = locale.TrString("mail.actions.successful_run_after_failure_subject", run.Title, run.Repo.FullName())
50+
} else {
51+
subject = locale.TrString("mail.actions.not_successful_run", run.Title, run.Repo.FullName())
52+
}
53+
54+
commitSHA := run.CommitSHA
55+
if len(commitSHA) > 7 {
56+
commitSHA = commitSHA[:7]
57+
}
58+
branch := run.PrettyRef()
59+
60+
data := map[string]any{
61+
"locale": locale,
62+
"Link": run.HTMLURL(),
63+
"Subject": subject,
64+
"Language": locale.Language(),
65+
"RepoFullName": run.Repo.FullName(),
66+
"Run": run,
67+
"TriggerUserLink": run.TriggerUser.HTMLURL(),
68+
"LastRun": lastRun,
69+
"PriorStatus": priorStatus,
70+
"CommitSHA": commitSHA,
71+
"Branch": branch,
72+
"IsSuccess": run.Status.IsSuccess(),
73+
}
74+
75+
if err := bodyTemplates.ExecuteTemplate(&content, string(tplActionNowDone), data); err != nil {
76+
return err
77+
}
78+
79+
msg := NewMessage(to.EmailTo(), subject, content.String())
80+
msg.Info = subject
81+
SendAsync(msg)
82+
83+
return nil
84+
}
Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
// Copyright 2025 The Forgejo Authors. All rights reserved.
2+
// SPDX-License-Identifier: GPL-3.0-or-later
3+
4+
package mailer
5+
6+
import (
7+
"testing"
8+
9+
actions_model "forgejo.org/models/actions"
10+
"forgejo.org/models/db"
11+
repo_model "forgejo.org/models/repo"
12+
user_model "forgejo.org/models/user"
13+
"forgejo.org/modules/setting"
14+
notify_service "forgejo.org/services/notify"
15+
16+
"github.com/stretchr/testify/assert"
17+
"github.com/stretchr/testify/require"
18+
)
19+
20+
func getActionsNowDoneTestUsers(t *testing.T) []*user_model.User {
21+
t.Helper()
22+
newTriggerUser := new(user_model.User)
23+
newTriggerUser.Name = "new_trigger_user"
24+
newTriggerUser.Language = "en_US"
25+
newTriggerUser.IsAdmin = false
26+
newTriggerUser.Email = "[email protected]"
27+
newTriggerUser.LastLoginUnix = 1693648327
28+
newTriggerUser.CreatedUnix = 1693648027
29+
newTriggerUser.EmailNotificationsPreference = user_model.EmailNotificationsEnabled
30+
require.NoError(t, user_model.CreateUser(db.DefaultContext, newTriggerUser))
31+
32+
newOwner := new(user_model.User)
33+
newOwner.Name = "new_owner"
34+
newOwner.Language = "en_US"
35+
newOwner.IsAdmin = false
36+
newOwner.Email = "[email protected]"
37+
newOwner.LastLoginUnix = 1693648329
38+
newOwner.CreatedUnix = 1693648029
39+
newOwner.EmailNotificationsPreference = user_model.EmailNotificationsEnabled
40+
require.NoError(t, user_model.CreateUser(db.DefaultContext, newOwner))
41+
42+
return []*user_model.User{newTriggerUser, newOwner}
43+
}
44+
45+
func assertTranslatedLocaleMailActionsNowDone(t *testing.T, msgBody string) {
46+
AssertTranslatedLocale(t, msgBody, "mail.actions.successful_run_after_failure", "mail.actions.not_successful_run", "mail.actions.run_info_cur_status", "mail.actions.run_info_ref", "mail.actions.run_info_previous_status", "mail.actions.run_info_trigger", "mail.view_it_on")
47+
}
48+
49+
func TestActionRunNowDoneNotificationMail(t *testing.T) {
50+
ctx := t.Context()
51+
52+
users := getActionsNowDoneTestUsers(t)
53+
defer CleanUpUsers(ctx, users)
54+
triggerUser := users[0]
55+
ownerUser := users[1]
56+
57+
repo := repo_model.Repository{
58+
Name: "some repo",
59+
Description: "rockets are cool",
60+
Owner: ownerUser,
61+
OwnerID: ownerUser.ID,
62+
}
63+
64+
// Do some funky stuff with the action run's ids:
65+
// The run with the larger ID finished first.
66+
// This is odd but something that must work.
67+
run1 := &actions_model.ActionRun{ID: 2, Repo: &repo, RepoID: repo.ID, Title: "some workflow", TriggerUser: triggerUser, TriggerUserID: triggerUser.ID, Status: actions_model.StatusFailure, Stopped: 1745821796, TriggerEvent: "workflow_dispatch"}
68+
run2 := &actions_model.ActionRun{ID: 1, Repo: &repo, RepoID: repo.ID, Title: "some workflow", TriggerUser: triggerUser, TriggerUserID: triggerUser.ID, Status: actions_model.StatusSuccess, Stopped: 1745822796, TriggerEvent: "push"}
69+
70+
notify_service.RegisterNotifier(NewNotifier())
71+
72+
t.Run("DontSendNotificationEmailOnFirstActionSuccess", func(t *testing.T) {
73+
defer MockMailSettings(func(msgs ...*Message) {
74+
assert.Fail(t, "no mail should be sent")
75+
})()
76+
notify_service.ActionRunNowDone(ctx, run2, actions_model.StatusRunning, nil)
77+
})
78+
79+
t.Run("SendNotificationEmailOnActionRunFailed", func(t *testing.T) {
80+
mailSentToOwner := false
81+
mailSentToTriggerUser := false
82+
defer MockMailSettings(func(msgs ...*Message) {
83+
assert.LessOrEqual(t, len(msgs), 2)
84+
for _, msg := range msgs {
85+
switch msg.To {
86+
case triggerUser.EmailTo():
87+
assert.False(t, mailSentToTriggerUser, "sent mail twice")
88+
mailSentToTriggerUser = true
89+
case ownerUser.EmailTo():
90+
assert.False(t, mailSentToOwner, "sent mail twice")
91+
mailSentToOwner = true
92+
default:
93+
assert.Fail(t, "sent mail to unknown sender", msg.To)
94+
}
95+
assert.Contains(t, msg.Body, triggerUser.HTMLURL())
96+
assert.Contains(t, msg.Body, triggerUser.Name)
97+
// what happened
98+
assert.Contains(t, msg.Body, "failed")
99+
// new status of run
100+
assert.Contains(t, msg.Body, "failure")
101+
// prior status of this run
102+
assert.Contains(t, msg.Body, "waiting")
103+
assertTranslatedLocaleMailActionsNowDone(t, msg.Body)
104+
}
105+
})()
106+
notify_service.ActionRunNowDone(ctx, run1, actions_model.StatusWaiting, nil)
107+
assert.True(t, mailSentToOwner)
108+
assert.True(t, mailSentToTriggerUser)
109+
})
110+
111+
t.Run("SendNotificationEmailOnActionRunRecovered", func(t *testing.T) {
112+
mailSentToOwner := false
113+
mailSentToTriggerUser := false
114+
defer MockMailSettings(func(msgs ...*Message) {
115+
assert.LessOrEqual(t, len(msgs), 2)
116+
for _, msg := range msgs {
117+
switch msg.To {
118+
case triggerUser.EmailTo():
119+
assert.False(t, mailSentToTriggerUser, "sent mail twice")
120+
mailSentToTriggerUser = true
121+
case ownerUser.EmailTo():
122+
assert.False(t, mailSentToOwner, "sent mail twice")
123+
mailSentToOwner = true
124+
default:
125+
assert.Fail(t, "sent mail to unknown sender", msg.To)
126+
}
127+
assert.Contains(t, msg.Body, triggerUser.HTMLURL())
128+
assert.Contains(t, msg.Body, triggerUser.Name)
129+
// what happened
130+
assert.Contains(t, msg.Body, "recovered")
131+
// old status of run
132+
assert.Contains(t, msg.Body, "failure")
133+
// new status of run
134+
assert.Contains(t, msg.Body, "success")
135+
// prior status of this run
136+
assert.Contains(t, msg.Body, "running")
137+
assertTranslatedLocaleMailActionsNowDone(t, msg.Body)
138+
}
139+
})()
140+
assert.NotNil(t, setting.MailService)
141+
142+
notify_service.ActionRunNowDone(ctx, run2, actions_model.StatusRunning, run1)
143+
assert.True(t, mailSentToOwner)
144+
assert.True(t, mailSentToTriggerUser)
145+
})
146+
}

services/mailer/mail_admin_new_user_test.go

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
package mailer
55

66
import (
7-
"context"
87
"strconv"
98
"testing"
109

@@ -17,7 +16,7 @@ import (
1716
"github.com/stretchr/testify/require"
1817
)
1918

20-
func getTestUsers(t *testing.T) []*user_model.User {
19+
func getAdminNewUserTestUsers(t *testing.T) []*user_model.User {
2120
t.Helper()
2221
admin := new(user_model.User)
2322
admin.Name = "testadmin"
@@ -38,16 +37,10 @@ func getTestUsers(t *testing.T) []*user_model.User {
3837
return []*user_model.User{admin, newUser}
3938
}
4039

41-
func cleanUpUsers(ctx context.Context, users []*user_model.User) {
42-
for _, u := range users {
43-
db.DeleteByID[user_model.User](ctx, u.ID)
44-
}
45-
}
46-
4740
func TestAdminNotificationMail_test(t *testing.T) {
4841
ctx := t.Context()
4942

50-
users := getTestUsers(t)
43+
users := getAdminNewUserTestUsers(t)
5144

5245
t.Run("SendNotificationEmailOnNewUser_true", func(t *testing.T) {
5346
defer test.MockVariableValue(&setting.Admin.SendNotificationEmailOnNewUser, true)()
@@ -75,5 +68,5 @@ func TestAdminNotificationMail_test(t *testing.T) {
7568
MailNewUser(ctx, users[1])
7669
})
7770

78-
cleanUpUsers(ctx, users)
71+
CleanUpUsers(ctx, users)
7972
}

services/mailer/main_test.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,9 @@ import (
77
"context"
88
"testing"
99

10+
"forgejo.org/models/db"
1011
"forgejo.org/models/unittest"
12+
user_model "forgejo.org/models/user"
1113
"forgejo.org/modules/setting"
1214
"forgejo.org/modules/templates"
1315
"forgejo.org/modules/test"
@@ -46,3 +48,9 @@ func MockMailSettings(send func(msgs ...*Message)) func() {
4648
}
4749
}
4850
}
51+
52+
func CleanUpUsers(ctx context.Context, users []*user_model.User) {
53+
for _, u := range users {
54+
db.DeleteByID[user_model.User](ctx, u.ID)
55+
}
56+
}

services/mailer/notify.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"context"
88
"fmt"
99

10+
actions_model "forgejo.org/models/actions"
1011
activities_model "forgejo.org/models/activities"
1112
issues_model "forgejo.org/models/issues"
1213
repo_model "forgejo.org/models/repo"
@@ -208,3 +209,13 @@ func (m *mailNotifier) RepoPendingTransfer(ctx context.Context, doer, newOwner *
208209
func (m *mailNotifier) NewUserSignUp(ctx context.Context, newUser *user_model.User) {
209210
MailNewUser(ctx, newUser)
210211
}
212+
213+
func (m *mailNotifier) ActionRunNowDone(ctx context.Context, run *actions_model.ActionRun, priorStatus actions_model.Status, lastRun *actions_model.ActionRun) {
214+
// Only send a mail on a successful run when the workflow recovered (i.e., the run before failed).
215+
if run.Status.IsSuccess() && (lastRun == nil || lastRun.Status.IsSuccess()) {
216+
return
217+
}
218+
if err := MailActionRun(run, priorStatus, lastRun); err != nil {
219+
log.Error("MailActionRunNowDone: %v", err)
220+
}
221+
}

templates/mail/actions/now_done.tmpl

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<!DOCTYPE html>
2+
<html>
3+
<head>
4+
<style>
5+
.footer { font-size:small; color:#666;}
6+
</style>
7+
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
8+
</head>
9+
10+
{{$repo_link := HTMLFormat "<a href='%s'>%s</a>" .Run.Repo.HTMLURL .RepoFullName}}
11+
{{$action_run_link := HTMLFormat "<a href='%s'>%s</a>" .Link .Run.Title}}
12+
{{$trigger_user_link := HTMLFormat "<a href='%s'>@%s</a>" .Run.TriggerUser.HTMLURL .Run.TriggerUser.Name}}
13+
<body>
14+
<p>
15+
{{if .IsSuccess}}
16+
{{.locale.Tr "mail.actions.successful_run_after_failure" $action_run_link $repo_link}}
17+
{{else}}
18+
{{.locale.Tr "mail.actions.not_successful_run" $action_run_link $repo_link}}
19+
{{end}}
20+
21+
<br />
22+
23+
{{.locale.Tr "mail.actions.run_info_cur_status" .Run.Status .PriorStatus}}<br />
24+
{{.locale.Tr "mail.actions.run_info_ref" .Branch .CommitSHA}}<br />
25+
{{if .LastRun}}
26+
{{.locale.Tr "mail.actions.run_info_previous_status" .LastRun.Status}}<br />
27+
{{end}}
28+
{{.locale.Tr "mail.actions.run_info_trigger" .Run.TriggerEvent $trigger_user_link}}
29+
</p>
30+
<div class="footer">
31+
<p>
32+
---
33+
<br>
34+
<a href="{{.Link}}">{{.locale.Tr "mail.view_it_on" AppName}}</a>.
35+
</p>
36+
</div>
37+
</body>
38+
</html>

0 commit comments

Comments
 (0)