mirror of
https://github.com/go-gitea/gitea.git
synced 2026-12-04 15:54:57 +00:00
enhance(webhooks): show live delivery status in history (#40389)
A webhook delivery looked failed while its HTTP request was still in flight. Recent Deliveries now tells the states apart and refreshes in place while a delivery is pending. - Rows show queued, in progress, succeeded or failed, plus the HTTP status code - Transport failures show as timed out, connection failed or blocked by the outbound request policy - Test Push Event and the 5s polling update the list without a page reload - Details open in a dialog, times render in the viewer's timezone | | Before | After | |-|-|-| | List | <img width="600" alt="Recent deliveries before" src="https://github.com/user-attachments/assets/c5fa2217-91d4-4278-bdd2-fc7e98f47bd7" /> | <img width="600" alt="Recent deliveries after" src="https://github.com/user-attachments/assets/0b91706e-ab5b-4fed-97f0-30c28e374f50" /> | | Details | <img width="600" alt="Delivery details before" src="https://github.com/user-attachments/assets/04fcae63-de09-4906-96d9-bcea4e15550f" /> | <img width="216" height="207" alt="Delivery details after" src="https://github.com/user-attachments/assets/9c0f68a4-2dcf-4fd3-b4e0-31f4f031465f" /> | Fixes: https://github.com/go-gitea/gitea/issues/40013 Assisted-by: Codex:GPT-6, Claude Code:claude-opus-5-5 --------- Co-authored-by: wxiaoguang <wxiaoguang@gmail.com> Co-authored-by: silverwind <me@silverwind.io>
This commit is contained in:
10 files changed
+343
-138
No files matched your search
+56
-11
@@ -6,14 +6,17 @@ package webhook
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"html/template"
|
||||
"time"
|
||||
"uuid"
|
||||
|
||||
"gitea.dev/models/db"
|
||||
"gitea.dev/modules/htmlutil"
|
||||
"gitea.dev/modules/json"
|
||||
"gitea.dev/modules/log"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/timeutil"
|
||||
"gitea.dev/modules/translation"
|
||||
webhook_module "gitea.dev/modules/webhook"
|
||||
|
||||
"xorm.io/builder"
|
||||
@@ -32,13 +35,6 @@ func (opts ListHookTaskOptions) ToOrders() string {
|
||||
return "hook_task.id DESC"
|
||||
}
|
||||
|
||||
// ___ ___ __ ___________ __
|
||||
// / | \ ____ ____ | | _\__ ___/____ _____| | __
|
||||
// / ~ \/ _ \ / _ \| |/ / | | \__ \ / ___/ |/ /
|
||||
// \ Y ( <_> | <_> ) < | | / __ \_\___ \| <
|
||||
// \___|_ / \____/ \____/|__|_ \ |____| (____ /____ >__|_ \
|
||||
// \/ \/ \/ \/ \/
|
||||
|
||||
// HookRequest represents hook task request information.
|
||||
type HookRequest struct {
|
||||
URL string `json:"url"`
|
||||
@@ -47,11 +43,21 @@ type HookRequest struct {
|
||||
Body string `json:"body"`
|
||||
}
|
||||
|
||||
type HookDeliveryError string
|
||||
|
||||
const (
|
||||
HookDeliveryErrorTimeout HookDeliveryError = "timeout"
|
||||
HookDeliveryErrorConnection HookDeliveryError = "connection"
|
||||
HookDeliveryErrorBlocked HookDeliveryError = "blocked"
|
||||
HookDeliveryErrorUnknown HookDeliveryError = "unknown"
|
||||
)
|
||||
|
||||
// HookResponse represents hook task response information.
|
||||
type HookResponse struct {
|
||||
Status int `json:"status"`
|
||||
Headers map[string]string `json:"headers"`
|
||||
Body string `json:"body"`
|
||||
Status int `json:"status"`
|
||||
Headers map[string]string `json:"headers"`
|
||||
Body string `json:"body"`
|
||||
ErrorType HookDeliveryError `json:"error_type,omitempty"`
|
||||
}
|
||||
|
||||
// HookTask represents a hook task.
|
||||
@@ -77,6 +83,44 @@ type HookTask struct {
|
||||
ResponseInfo *HookResponse `xorm:"-"`
|
||||
}
|
||||
|
||||
func (t *HookTask) IsDeliveryInProgress() bool {
|
||||
if !t.IsDelivered || t.ResponseContent != "" {
|
||||
return false
|
||||
}
|
||||
// Legacy claims only recorded the time the delivery was queued.
|
||||
timeout := time.Duration(setting.Webhook.DeliverTimeout) * time.Second
|
||||
return timeout <= 0 || time.Since(t.Delivered.AsTime()) < timeout+10*time.Second
|
||||
}
|
||||
|
||||
func (t *HookTask) IsDeliveryWaitingForResult() bool {
|
||||
return !t.IsDelivered || t.IsDeliveryInProgress()
|
||||
}
|
||||
|
||||
func (t *HookTask) DeliveryStatusTr(locale translation.Locale) template.HTML {
|
||||
if t.ResponseInfo != nil && t.ResponseInfo.ErrorType != "" {
|
||||
switch t.ResponseInfo.ErrorType {
|
||||
case HookDeliveryErrorTimeout:
|
||||
return locale.Tr("repo.settings.webhook.delivery.timeout")
|
||||
case HookDeliveryErrorConnection:
|
||||
return locale.Tr("repo.settings.webhook.delivery.connection")
|
||||
case HookDeliveryErrorBlocked:
|
||||
return locale.Tr("repo.settings.webhook.delivery.blocked")
|
||||
default:
|
||||
return htmlutil.EscapeString(string(t.ResponseInfo.ErrorType))
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case t.IsSucceed:
|
||||
return locale.Tr("repo.settings.webhook.delivery.succeeded")
|
||||
case !t.IsDelivered:
|
||||
return locale.Tr("repo.settings.webhook.delivery.queued")
|
||||
case t.IsDeliveryInProgress():
|
||||
return locale.Tr("repo.settings.webhook.delivery.in_progress")
|
||||
default:
|
||||
return locale.Tr("repo.settings.webhook.delivery.failed")
|
||||
}
|
||||
}
|
||||
|
||||
func init() {
|
||||
db.RegisterModel(new(HookTask))
|
||||
}
|
||||
@@ -207,9 +251,10 @@ func FindUndeliveredHookTaskIDs(ctx context.Context, lowerID int64) ([]int64, er
|
||||
}
|
||||
|
||||
func MarkTaskDelivered(ctx context.Context, task *HookTask) (bool, error) {
|
||||
count, err := db.GetEngine(ctx).ID(task.ID).Where("is_delivered = ?", false).Cols("is_delivered").Update(&HookTask{
|
||||
count, err := db.GetEngine(ctx).ID(task.ID).Where("is_delivered = ?", false).Cols("is_delivered", "delivered").Update(&HookTask{
|
||||
ID: task.ID,
|
||||
IsDelivered: true,
|
||||
Delivered: timeutil.TimeStampNanoNow(),
|
||||
})
|
||||
|
||||
return count != 0, err
|
||||
|
||||
@@ -2303,6 +2303,13 @@
|
||||
"repo.settings.webhook.replay.description": "Replay this webhook.",
|
||||
"repo.settings.webhook.replay.description_disabled": "To replay this webhook, activate it.",
|
||||
"repo.settings.webhook.delivery.success": "An event has been added to the delivery queue. It may take few seconds before it shows up in the delivery history.",
|
||||
"repo.settings.webhook.delivery.queued": "Queued",
|
||||
"repo.settings.webhook.delivery.in_progress": "In progress",
|
||||
"repo.settings.webhook.delivery.succeeded": "Succeeded",
|
||||
"repo.settings.webhook.delivery.failed": "Failed",
|
||||
"repo.settings.webhook.delivery.timeout": "Timed out",
|
||||
"repo.settings.webhook.delivery.connection": "Connection failed",
|
||||
"repo.settings.webhook.delivery.blocked": "Blocked by outbound request policy",
|
||||
"repo.settings.githooks_desc": "Git Hooks are powered by Git itself. You can edit hook files below to set up custom operations.",
|
||||
"repo.settings.githook_edit_desc": "If the hook is inactive, sample content will be presented. Leaving content to an empty value will disable this hook.",
|
||||
"repo.settings.update_githook": "Update Hook",
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"gitea.dev/models/db"
|
||||
@@ -35,6 +36,7 @@ import (
|
||||
|
||||
const (
|
||||
tplHooks templates.TplName = "repo/settings/webhook/base"
|
||||
tplHookHistory templates.TplName = "repo/settings/webhook/history"
|
||||
tplHookNew templates.TplName = "repo/settings/webhook/new"
|
||||
tplOrgHookNew templates.TplName = "org/settings/hook_new"
|
||||
tplUserHookNew templates.TplName = "user/settings/hook_new"
|
||||
@@ -286,11 +288,8 @@ func editWebhook(ctx *context.Context, params webhookParams) {
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
orCtx.setFormPageData(ctx, false, w.IsSystemWebhook)
|
||||
ctx.Data["Webhook"] = w
|
||||
|
||||
if ctx.HasError() {
|
||||
ctx.HTML(http.StatusOK, orCtx.NewTemplate)
|
||||
renderWebhookEdit(ctx, orCtx, w)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -631,7 +630,58 @@ func checkWebhook(ctx *context.Context) (*ownerRepoCtx, *webhook.Webhook) {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return nil, nil
|
||||
}
|
||||
return orCtx, w
|
||||
}
|
||||
|
||||
func loadWebhookHistory(ctx *context.Context, orCtx *ownerRepoCtx, w *webhook.Webhook) bool {
|
||||
tasks, err := w.History(ctx, 1)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return false
|
||||
}
|
||||
|
||||
hasWaiting := slices.ContainsFunc(tasks, (*webhook.HookTask).IsDeliveryWaitingForResult)
|
||||
refreshSeconds := util.Iif(hasWaiting, 5, 0)
|
||||
if refreshSeconds != 0 && !setting.IsProd {
|
||||
refreshSeconds = 1
|
||||
}
|
||||
|
||||
ctx.Data["Webhook"] = w
|
||||
ctx.Data["WebhookLink"] = fmt.Sprintf("%s/%d", orCtx.Link, w.ID)
|
||||
ctx.Data["WebhookHistoryRefreshSeconds"] = refreshSeconds
|
||||
ctx.Data["History"] = tasks
|
||||
return true
|
||||
}
|
||||
|
||||
func renderWebhookHistory(ctx *context.Context, orCtx *ownerRepoCtx, w *webhook.Webhook) {
|
||||
if loadWebhookHistory(ctx, orCtx, w) {
|
||||
ctx.HTML(http.StatusOK, tplHookHistory)
|
||||
}
|
||||
}
|
||||
|
||||
// WebhookHistory renders the recent deliveries fragment.
|
||||
func WebhookHistory(ctx *context.Context) {
|
||||
orCtx, w := checkWebhook(ctx)
|
||||
if !ctx.Written() {
|
||||
renderWebhookHistory(ctx, orCtx, w)
|
||||
}
|
||||
}
|
||||
|
||||
// WebHooksEdit render editing web hook page
|
||||
func WebHooksEdit(ctx *context.Context) {
|
||||
ctx.Data["PageIsSettingsHooksEdit"] = true
|
||||
|
||||
orCtx, w := checkWebhook(ctx)
|
||||
if !ctx.Written() {
|
||||
renderWebhookEdit(ctx, orCtx, w)
|
||||
}
|
||||
}
|
||||
|
||||
func renderWebhookEdit(ctx *context.Context, orCtx *ownerRepoCtx, w *webhook.Webhook) {
|
||||
if !loadWebhookHistory(ctx, orCtx, w) {
|
||||
return
|
||||
}
|
||||
orCtx.setFormPageData(ctx, false, w.IsSystemWebhook)
|
||||
ctx.Data["HookType"] = w.Type
|
||||
switch w.Type {
|
||||
case webhook_module.SLACK:
|
||||
@@ -645,35 +695,13 @@ func checkWebhook(ctx *context.Context) (*ownerRepoCtx, *webhook.Webhook) {
|
||||
case webhook_module.PACKAGIST:
|
||||
ctx.Data["PackagistHook"] = webhook_service.GetPackagistHook(w)
|
||||
}
|
||||
|
||||
ctx.Data["History"], err = w.History(ctx, 1)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
}
|
||||
return orCtx, w
|
||||
}
|
||||
|
||||
// WebHooksEdit render editing web hook page
|
||||
func WebHooksEdit(ctx *context.Context) {
|
||||
ctx.Data["PageIsSettingsHooksEdit"] = true
|
||||
|
||||
orCtx, w := checkWebhook(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
orCtx.setFormPageData(ctx, false, w.IsSystemWebhook)
|
||||
ctx.Data["Webhook"] = w
|
||||
|
||||
ctx.HTML(http.StatusOK, orCtx.NewTemplate)
|
||||
}
|
||||
|
||||
// TestWebhook test if web hook is work fine
|
||||
func TestWebhook(ctx *context.Context) {
|
||||
hookID := ctx.PathParamInt64("id")
|
||||
w, err := webhook.GetWebhookByRepoID(ctx, ctx.Repo.Repository.ID, hookID)
|
||||
if err != nil {
|
||||
ctx.Flash.Error("GetWebhookByRepoID: " + err.Error())
|
||||
ctx.Status(http.StatusInternalServerError)
|
||||
orCtx, w := checkWebhook(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -717,12 +745,10 @@ func TestWebhook(ctx *context.Context) {
|
||||
Sender: apiUser,
|
||||
}
|
||||
if err := webhook_service.PrepareTestWebhook(ctx, w, webhook_module.HookEventPush, p); err != nil {
|
||||
ctx.Flash.Error("PrepareTestWebhook: " + err.Error())
|
||||
ctx.Status(http.StatusInternalServerError)
|
||||
} else {
|
||||
ctx.Flash.Info(ctx.Tr("repo.settings.webhook.delivery.success"))
|
||||
ctx.Status(http.StatusOK)
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
renderWebhookHistory(ctx, orCtx, w)
|
||||
}
|
||||
|
||||
// ReplayWebhook replays a webhook
|
||||
|
||||
@@ -709,6 +709,7 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) {
|
||||
addWebhookAddRoutes()
|
||||
m.Group("/{id}", func() {
|
||||
m.Get("", repo_setting.WebHooksEdit)
|
||||
m.Get("/history", repo_setting.WebhookHistory)
|
||||
m.Post("/replay/{uuid}", repo_setting.ReplayWebhook)
|
||||
})
|
||||
addWebhookEditRoutes()
|
||||
@@ -831,6 +832,7 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) {
|
||||
m.Post("/delete", admin.DeleteDefaultOrSystemWebhook)
|
||||
m.Group("/{id}", func() {
|
||||
m.Get("", repo_setting.WebHooksEdit)
|
||||
m.Get("/history", repo_setting.WebhookHistory)
|
||||
m.Post("/replay/{uuid}", repo_setting.ReplayWebhook)
|
||||
})
|
||||
addWebhookEditRoutes()
|
||||
@@ -1009,6 +1011,7 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) {
|
||||
addWebhookAddRoutes()
|
||||
m.Group("/{id}", func() {
|
||||
m.Get("", repo_setting.WebHooksEdit)
|
||||
m.Get("/history", repo_setting.WebhookHistory)
|
||||
m.Post("/replay/{uuid}", repo_setting.ReplayWebhook)
|
||||
})
|
||||
addWebhookEditRoutes()
|
||||
@@ -1207,6 +1210,7 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) {
|
||||
addWebhookAddRoutes()
|
||||
m.Group("/{id}", func() {
|
||||
m.Get("", repo_setting.WebHooksEdit)
|
||||
m.Get("/history", repo_setting.WebhookHistory)
|
||||
m.Post("/test", repo_setting.TestWebhook)
|
||||
m.Post("/replay/{uuid}", repo_setting.ReplayWebhook)
|
||||
})
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
@@ -21,6 +22,7 @@ import (
|
||||
user_model "gitea.dev/models/user"
|
||||
webhook_model "gitea.dev/models/webhook"
|
||||
"gitea.dev/modules/egress"
|
||||
"gitea.dev/modules/egress/policy"
|
||||
"gitea.dev/modules/graceful"
|
||||
"gitea.dev/modules/log"
|
||||
"gitea.dev/modules/process"
|
||||
@@ -211,6 +213,10 @@ func Deliver(ctx context.Context, t *webhook_model.HookTask) error {
|
||||
|
||||
// All code from this point will update the hook task
|
||||
defer func() {
|
||||
if ctx.Err() != nil {
|
||||
return // when shutdown, no need to update the database
|
||||
}
|
||||
|
||||
t.Delivered = timeutil.TimeStampNanoNow()
|
||||
if t.IsSucceed {
|
||||
log.Trace("Hook delivered: %s", t.UUID)
|
||||
@@ -248,6 +254,7 @@ func Deliver(ctx context.Context, t *webhook_model.HookTask) error {
|
||||
resp, err := webhookHTTPClient.Do(req.WithContext(ctx))
|
||||
if err != nil {
|
||||
t.ResponseInfo.Body = fmt.Sprintf("Delivery: %v", err)
|
||||
t.ResponseInfo.ErrorType = deliveryErrorType(err)
|
||||
return fmt.Errorf("unable to deliver webhook task[%d] in %s due to error in http client: %w", t.ID, w.URL, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
@@ -268,6 +275,23 @@ func Deliver(ctx context.Context, t *webhook_model.HookTask) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func deliveryErrorType(err error) webhook_model.HookDeliveryError {
|
||||
if errors.Is(err, policy.ErrDenied) {
|
||||
return webhook_model.HookDeliveryErrorBlocked
|
||||
}
|
||||
if netErr, ok := errors.AsType[net.Error](err); ok && netErr.Timeout() {
|
||||
return webhook_model.HookDeliveryErrorTimeout
|
||||
}
|
||||
if _, ok := errors.AsType[*net.OpError](err); ok {
|
||||
return webhook_model.HookDeliveryErrorConnection
|
||||
}
|
||||
if errors.Is(err, context.Canceled) {
|
||||
return webhook_model.HookDeliveryErrorUnknown
|
||||
}
|
||||
setting.PanicInDevOrTesting("Unknown error type in webhook delivery: %v", err)
|
||||
return webhook_model.HookDeliveryErrorUnknown
|
||||
}
|
||||
|
||||
var webhookHTTPClient *http.Client
|
||||
|
||||
// Init starts the hooks delivery thread
|
||||
|
||||
@@ -13,10 +13,14 @@ import (
|
||||
|
||||
"gitea.dev/models/unittest"
|
||||
webhook_model "gitea.dev/models/webhook"
|
||||
"gitea.dev/modules/egress"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/test"
|
||||
"gitea.dev/modules/util"
|
||||
webhook_module "gitea.dev/modules/webhook"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestWebhookDeliverAuthorizationHeader(t *testing.T) {
|
||||
@@ -191,6 +195,47 @@ func TestWebhookDeliverHookTask(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebhookDeliveryErrorType(t *testing.T) {
|
||||
require.NoError(t, unittest.PrepareTestDatabase())
|
||||
stalled := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
<-r.Context().Done()
|
||||
}))
|
||||
t.Cleanup(stalled.Close)
|
||||
closed := httptest.NewServer(http.NotFoundHandler())
|
||||
closed.Close()
|
||||
|
||||
timeoutClient := *webhookHTTPClient
|
||||
timeoutClient.Timeout = 50 * time.Millisecond
|
||||
restoreAllowList := test.MockVariableValue(&setting.Webhook.AllowedHostList, "")
|
||||
blockedClient := &http.Client{Transport: egress.NewWebhookPolicy().NewHTTPTransport()}
|
||||
restoreAllowList()
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
client *http.Client
|
||||
url string
|
||||
errorType webhook_model.HookDeliveryError
|
||||
}{
|
||||
{"blocked", blockedClient, stalled.URL, webhook_model.HookDeliveryErrorBlocked},
|
||||
{"timeout", &timeoutClient, stalled.URL, webhook_model.HookDeliveryErrorTimeout},
|
||||
{"connection", webhookHTTPClient, closed.URL, webhook_model.HookDeliveryErrorConnection},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
defer test.MockVariableValue(&webhookHTTPClient, tc.client)()
|
||||
hook := &webhook_model.Webhook{RepoID: 3, URL: tc.url, ContentType: webhook_model.ContentTypeJSON, Events: `{}`, IsActive: true}
|
||||
require.NoError(t, webhook_model.CreateWebhook(t.Context(), hook))
|
||||
task, err := webhook_model.CreateHookTask(t.Context(), &webhook_model.HookTask{HookID: hook.ID, EventType: webhook_module.HookEventPush, PayloadVersion: 1})
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Error(t, Deliver(t.Context(), task))
|
||||
stored, err := webhook_model.GetHookTaskByID(t.Context(), task.ID)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, stored.ResponseInfo)
|
||||
assert.Equal(t, tc.errorType, stored.ResponseInfo.ErrorType)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebhookDeliverSpecificTypes(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
|
||||
@@ -1,87 +1,81 @@
|
||||
{{if .PageIsSettingsHooksEdit}}
|
||||
<h4 class="ui top attached header flex-left-right">
|
||||
<span>{{ctx.Locale.Tr "repo.settings.recent_deliveries"}}</span>
|
||||
{{if .Permission.IsAdmin}}
|
||||
<button type="button" class="ui tiny button" data-link="{{.Link}}/test" data-global-click="onWebhookTestDeliveryClick"
|
||||
data-tooltip-content="{{ctx.Locale.Tr "repo.settings.webhook.test_delivery_desc"}}"
|
||||
>
|
||||
{{ctx.Locale.Tr "repo.settings.webhook.test_delivery"}}
|
||||
</button>
|
||||
{{end}}
|
||||
</h4>
|
||||
<div class="ui attached segment">
|
||||
<div class="flex-divided-list">
|
||||
{{range .History}}
|
||||
<div class="item">
|
||||
<div class="flex-left-right">
|
||||
<div class="flex-text-inline">
|
||||
{{if .IsSucceed}}
|
||||
<span class="tw-text-green">{{svg "octicon-check"}}</span>
|
||||
{{else if not .IsDelivered}}
|
||||
<span class="tw-text-orange">{{svg "octicon-stopwatch"}}</span>
|
||||
{{else}}
|
||||
<span class="tw-text-red">{{svg "octicon-alert"}}</span>
|
||||
{{end}}
|
||||
<button type="button" class="btn interact-bg tw-p-2 toggle show-panel" data-panel="#webhook-history-info-{{.ID}}">{{.UUID}}</button>
|
||||
</div>
|
||||
<div class="ui attached segment" id="webhook-history"
|
||||
{{if .WebhookHistoryRefreshSeconds}}data-fetch-url="{{.WebhookLink}}/history" data-fetch-trigger="every {{.WebhookHistoryRefreshSeconds}}s"{{end}}
|
||||
>
|
||||
{{$canReplay := or $.Permission.IsAdmin $.IsOrganizationOwner $.PageIsAdmin $.PageIsUserSettings}}
|
||||
<div class="flex-divided-list">
|
||||
{{range $history := .History}}
|
||||
{{$reqInfo := $history.RequestInfo}}
|
||||
{{$respInfo := $history.ResponseInfo}}
|
||||
<div class="item" id="webhook-history-delivery-{{$history.ID}}">
|
||||
<div class="flex-left-right">
|
||||
<div class="flex-text-inline tw-flex-wrap">
|
||||
{{if $history.IsSucceed}}
|
||||
<span class="tw-text-green">{{svg "octicon-check"}}</span>
|
||||
{{else if $history.IsDeliveryWaitingForResult}}
|
||||
<span class="tw-text-text-light">{{svg "octicon-stopwatch"}}</span>
|
||||
{{else}}
|
||||
<span class="tw-text-red">{{svg "octicon-alert"}}</span>
|
||||
{{end}}
|
||||
<button type="button" class="btn interact-bg tw-p-2 show-modal" aria-haspopup="dialog" data-modal="#webhook-delivery-details-{{$history.ID}}">{{$history.UUID}}</button>
|
||||
<span class="tw-text-text-light">
|
||||
{{DateUtils.TimeSince .Delivered}}
|
||||
{{$history.DeliveryStatusTr ctx.Locale}}
|
||||
</span>
|
||||
{{if and $respInfo $respInfo.Status}}
|
||||
<span class="ui {{if $history.IsSucceed}}green{{else}}red{{end}} label">{{$respInfo.Status}}</span>
|
||||
{{end}}
|
||||
</div>
|
||||
<div class="info tw-hidden tw-mt-2" id="webhook-history-info-{{.ID}}">
|
||||
<div class="ui top attached tabular menu" data-global-init="initTabSwitcher">
|
||||
<a class="item active" data-tab="webhook-history-request-{{.ID}}">
|
||||
{{template "shared/misc/tabtitle" (ctx.Locale.Tr "repo.settings.webhook.request")}}
|
||||
</a>
|
||||
<a class="item" data-tab="webhook-history-response-{{.ID}}">
|
||||
{{template "shared/misc/tabtitle" (ctx.Locale.Tr "repo.settings.webhook.response")}}
|
||||
{{if .ResponseInfo}}
|
||||
{{if .IsSucceed}}
|
||||
<span class="ui green label">{{.ResponseInfo.Status}}</span>
|
||||
{{else}}
|
||||
<span class="ui red label">{{.ResponseInfo.Status}}</span>
|
||||
{{end}}
|
||||
{{else}}
|
||||
<span class="ui label">-</span>
|
||||
{{end}}
|
||||
</a>
|
||||
{{if or $.Permission.IsAdmin $.IsOrganizationOwner $.PageIsAdmin $.PageIsUserSettings}}
|
||||
<div class="right menu">
|
||||
<form class="tw-py-2" action="{{$.Link}}/replay/{{.UUID}}" method="post">
|
||||
<span data-tooltip-content="{{if $.Webhook.IsActive}}{{ctx.Locale.Tr "repo.settings.webhook.replay.description"}}{{else}}{{ctx.Locale.Tr "repo.settings.webhook.replay.description_disabled"}}{{end}}">
|
||||
<button type="submit" class="ui tiny button tw-mr-0{{if not $.Webhook.IsActive}} disabled{{end}}">{{svg "octicon-sync"}}</button>
|
||||
</span>
|
||||
</form>
|
||||
</div>
|
||||
{{end}}
|
||||
</div>
|
||||
<div class="ui bottom attached tab segment active" data-tab="webhook-history-request-{{.ID}}">
|
||||
{{if .RequestInfo}}
|
||||
<h5>{{ctx.Locale.Tr "repo.settings.webhook.headers"}}</h5>
|
||||
<pre class="webhook-info"><strong>Request URL:</strong> {{.RequestInfo.URL}}
|
||||
<strong>Request method:</strong> {{if .RequestInfo.HTTPMethod}}{{.RequestInfo.HTTPMethod}}{{else}}POST{{end}}
|
||||
{{range $key, $val := .RequestInfo.Headers}}<strong>{{$key}}:</strong> {{$val}}
|
||||
{{end}}</pre>
|
||||
<h5>{{ctx.Locale.Tr "repo.settings.webhook.payload"}}</h5>
|
||||
<pre class="webhook-info">{{or .RequestInfo.Body .PayloadContent}}</pre>
|
||||
{{else}}
|
||||
-
|
||||
{{end}}
|
||||
</div>
|
||||
<div class="ui bottom attached tab segment" data-tab="webhook-history-response-{{.ID}}">
|
||||
{{if .ResponseInfo}}
|
||||
<h5>{{ctx.Locale.Tr "repo.settings.webhook.headers"}}</h5>
|
||||
<pre class="webhook-info">{{range $key, $val := .ResponseInfo.Headers}}<strong>{{$key}}:</strong> {{$val}}
|
||||
{{else}}(no response header){{end}}</pre>
|
||||
<h5>{{ctx.Locale.Tr "repo.settings.webhook.body"}}</h5>
|
||||
<pre class="webhook-info">{{or .ResponseInfo.Body "(no response body)"}}</pre>
|
||||
{{else}}
|
||||
-
|
||||
{{end}}
|
||||
</div>
|
||||
</div>
|
||||
<span class="tw-text-text-light">{{DateUtils.FullTime $history.Delivered}}</span>
|
||||
</div>
|
||||
{{end}}
|
||||
</div>
|
||||
|
||||
<template id="webhook-delivery-details-{{$history.ID}}">
|
||||
<dialog class="modal-dialog">
|
||||
<div class="header">{{$history.UUID}} <button type="button" class="close-modal"></button></div>
|
||||
<div class="content">
|
||||
<div class="ui top attached tabular menu" data-global-init="initTabSwitcher">
|
||||
<a class="item active" data-tab="webhook-history-request-{{$history.ID}}">
|
||||
{{template "shared/misc/tabtitle" (ctx.Locale.Tr "repo.settings.webhook.request")}}
|
||||
</a>
|
||||
<a class="item" data-tab="webhook-history-response-{{$history.ID}}">
|
||||
{{template "shared/misc/tabtitle" (ctx.Locale.Tr "repo.settings.webhook.response")}}
|
||||
</a>
|
||||
{{if $canReplay}}
|
||||
<div class="right menu">
|
||||
<form class="tw-py-2" action="{{$.WebhookLink}}/replay/{{$history.UUID}}" method="post">
|
||||
<span data-tooltip-content="{{if $.Webhook.IsActive}}{{ctx.Locale.Tr "repo.settings.webhook.replay.description"}}{{else}}{{ctx.Locale.Tr "repo.settings.webhook.replay.description_disabled"}}{{end}}">
|
||||
<button type="submit" class="ui tiny button tw-mr-0{{if not $.Webhook.IsActive}} disabled{{end}}">{{svg "octicon-sync"}}</button>
|
||||
</span>
|
||||
</form>
|
||||
</div>
|
||||
{{end}}
|
||||
</div>
|
||||
<div class="ui bottom attached tab segment active" data-tab="webhook-history-request-{{$history.ID}}">
|
||||
{{if $reqInfo}}
|
||||
<h5>{{ctx.Locale.Tr "repo.settings.webhook.headers"}}</h5>
|
||||
<pre class="webhook-info"><strong>Request URL:</strong> {{$reqInfo.URL}}
|
||||
<strong>Request method:</strong> {{if $reqInfo.HTTPMethod}}{{$reqInfo.HTTPMethod}}{{else}}POST{{end}}
|
||||
{{range $key, $val := $reqInfo.Headers}}<strong>{{$key}}:</strong> {{$val}}
|
||||
{{end}}</pre>
|
||||
<h5>{{ctx.Locale.Tr "repo.settings.webhook.payload"}}</h5>
|
||||
<pre class="webhook-info">{{or $reqInfo.Body $history.PayloadContent}}</pre>
|
||||
{{else}}
|
||||
-
|
||||
{{end}}
|
||||
</div>
|
||||
<div class="ui bottom attached tab segment" data-tab="webhook-history-response-{{$history.ID}}">
|
||||
{{if $respInfo}}
|
||||
<h5>{{ctx.Locale.Tr "repo.settings.webhook.headers"}}</h5>
|
||||
<pre class="webhook-info">{{range $key, $val := $respInfo.Headers}}<strong>{{$key}}:</strong> {{$val}}
|
||||
{{else}}(no response header){{end}}</pre>
|
||||
<h5>{{ctx.Locale.Tr "repo.settings.webhook.body"}}</h5>
|
||||
<pre class="webhook-info">{{or $respInfo.Body "(no response body)"}}</pre>
|
||||
{{else}}
|
||||
-
|
||||
{{end}}
|
||||
</div>
|
||||
</div>
|
||||
</dialog>
|
||||
</template>
|
||||
</div>
|
||||
{{end}}
|
||||
</div>
|
||||
{{end}}
|
||||
</div>
|
||||
@@ -22,4 +22,16 @@
|
||||
{{template "repo/settings/webhook/wechatwork" ctx.RootData}}
|
||||
{{template "repo/settings/webhook/packagist" ctx.RootData}}
|
||||
</div>
|
||||
{{template "repo/settings/webhook/history" ctx.RootData}}
|
||||
{{if ctx.RootData.PageIsSettingsHooksEdit}}
|
||||
<h4 class="ui top attached header flex-left-right">
|
||||
<span>{{ctx.Locale.Tr "repo.settings.recent_deliveries"}}</span>
|
||||
{{if ctx.RootData.Permission.IsAdmin}}
|
||||
<button type="button" class="ui tiny button" data-fetch-url="{{ctx.RootData.WebhookLink}}/test" data-fetch-method="POST"
|
||||
data-fetch-sync="$body #webhook-history" data-tooltip-content="{{ctx.Locale.Tr "repo.settings.webhook.test_delivery_desc"}}"
|
||||
>
|
||||
{{ctx.Locale.Tr "repo.settings.webhook.test_delivery"}}
|
||||
</button>
|
||||
{{end}}
|
||||
</h4>
|
||||
{{template "repo/settings/webhook/history" ctx.RootData}}
|
||||
{{end}}
|
||||
@@ -30,6 +30,7 @@ import (
|
||||
"gitea.dev/modules/setting"
|
||||
api "gitea.dev/modules/structs"
|
||||
"gitea.dev/modules/test"
|
||||
"gitea.dev/modules/timeutil"
|
||||
webhook_module "gitea.dev/modules/webhook"
|
||||
"gitea.dev/services/actions"
|
||||
"gitea.dev/tests"
|
||||
@@ -67,6 +68,63 @@ func TestNewWebHookLink(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebhookDeliveryHistory(t *testing.T) {
|
||||
defer tests.PrepareTestEnv(t)()
|
||||
hook := &webhook.Webhook{
|
||||
RepoID: 1,
|
||||
URL: "http://localhost/webhook",
|
||||
ContentType: webhook.ContentTypeJSON,
|
||||
Type: webhook_module.GITEA,
|
||||
Events: `{}`,
|
||||
}
|
||||
require.NoError(t, webhook.CreateWebhook(t.Context(), hook))
|
||||
stale := timeutil.TimeStampNano(time.Now().Add(-time.Hour).UnixNano())
|
||||
queued, err := webhook.CreateHookTask(t.Context(), &webhook.HookTask{HookID: hook.ID, Delivered: stale, PayloadVersion: 1})
|
||||
require.NoError(t, err)
|
||||
interrupted, err := webhook.CreateHookTask(t.Context(), &webhook.HookTask{HookID: hook.ID, Delivered: stale, IsDelivered: true, PayloadVersion: 1})
|
||||
require.NoError(t, err)
|
||||
legacy, err := webhook.CreateHookTask(t.Context(), &webhook.HookTask{
|
||||
HookID: hook.ID, Delivered: stale, IsDelivered: true, PayloadVersion: 1,
|
||||
RequestContent: `{}`, ResponseContent: `{"status":0,"body":"Delivery: connection refused"}`,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
session := loginUser(t, "user2")
|
||||
hookURL := fmt.Sprintf("/user2/repo1/settings/hooks/%d", hook.ID)
|
||||
historyURL := hookURL + "/history"
|
||||
row := func(task *webhook.HookTask) string { return fmt.Sprintf("#webhook-history-delivery-%d", task.ID) }
|
||||
read := func(url string) *goquery.Selection {
|
||||
response := session.MakeRequest(t, NewRequest(t, "GET", url), http.StatusOK)
|
||||
return NewHTMLParser(t, response.Body).doc.Find("#webhook-history")
|
||||
}
|
||||
const poll = `[data-fetch-trigger="every 5s"]`
|
||||
history := read(hookURL)
|
||||
assert.Contains(t, history.Find(row(queued)).Text(), "Queued")
|
||||
assert.Contains(t, history.Find(row(interrupted)).Text(), "Failed")
|
||||
assert.Contains(t, history.Find(row(legacy)).Text(), "Failed")
|
||||
assert.Equal(t, historyURL, history.Filter(poll).AttrOr("data-fetch-url", ""))
|
||||
|
||||
claimed, err := webhook.MarkTaskDelivered(t.Context(), queued)
|
||||
require.NoError(t, err)
|
||||
require.True(t, claimed)
|
||||
history = read(historyURL)
|
||||
assert.Contains(t, history.Find(row(queued)).Text(), "In progress")
|
||||
assert.True(t, history.Is(poll))
|
||||
|
||||
queued.IsDelivered = true
|
||||
queued.RequestInfo = &webhook.HookRequest{}
|
||||
queued.ResponseInfo = &webhook.HookResponse{Status: http.StatusBadGateway}
|
||||
require.NoError(t, webhook.UpdateHookTask(t.Context(), queued))
|
||||
history = read(historyURL)
|
||||
assert.Contains(t, history.Find(row(queued)).Text(), "Failed")
|
||||
assert.Equal(t, "502", history.Find(row(queued)+" .ui.red.label").Text())
|
||||
assert.False(t, history.Is(poll))
|
||||
|
||||
response := session.MakeRequest(t, NewRequest(t, "POST", hookURL+"/test"), http.StatusOK)
|
||||
history = NewHTMLParser(t, response.Body).doc.Find("#webhook-history")
|
||||
assert.Equal(t, 4, history.Find(".flex-divided-list > .item").Length())
|
||||
}
|
||||
|
||||
func testAPICreateWebhookForRepo(t *testing.T, session *TestSession, userName, repoName, url, event string, branchFilter ...string) {
|
||||
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeAll)
|
||||
var branchFilterString string
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import {registerGlobalEventFunc, registerGlobalInitFunc} from '../../modules/observer.ts';
|
||||
import {POST} from '../../modules/fetch.ts';
|
||||
import {registerGlobalInitFunc} from '../../modules/observer.ts';
|
||||
import {queryElems, toggleElem} from '../../utils/dom.ts';
|
||||
|
||||
function initCompWebHookEditorForm(el: HTMLElement) {
|
||||
@@ -32,15 +31,6 @@ function initCompWebHookEditorForm(el: HTMLElement) {
|
||||
}
|
||||
}
|
||||
|
||||
function initCompWebHookEditorHistory() {
|
||||
registerGlobalEventFunc('click', 'onWebhookTestDeliveryClick', async (el) => {
|
||||
el.classList.add('is-loading', 'disabled');
|
||||
await POST(el.getAttribute('data-link')!);
|
||||
setTimeout(() => window.location.reload(), 5000);
|
||||
});
|
||||
}
|
||||
|
||||
export function initCompWebHookEditor() {
|
||||
registerGlobalInitFunc('initCompWebHookEditorForm', initCompWebHookEditorForm);
|
||||
initCompWebHookEditorHistory();
|
||||
}
|
||||
Reference in new issue
Block a user