refactor: queue

This commit is contained in:
tao.chen
2026-08-26 10:55:09 +08:00
parent 8c0e14987e
commit b25a889977
4 changed files with 83 additions and 45 deletions
+9 -37
View File
@@ -5,8 +5,6 @@ import (
"log"
"net/http"
"os"
"sync"
"time"
"github.com/gin-gonic/gin"
)
@@ -20,13 +18,6 @@ type GitLabPayload struct {
} `json:"project"`
}
// debounceEntry 单个 key 的冷却去重状态。
// lastExec:上次实际执行时刻;冷却窗口内到达的 push 直接丢弃,无补跑。
type debounceEntry struct {
mu sync.Mutex
lastExec time.Time
}
func handleWebhook(c *gin.Context) {
// 1. 校验 GitLab Secret Token Header
clientToken := c.GetHeader("X-Gitlab-Token")
@@ -77,37 +68,18 @@ func handleWebhook(c *gin.Context) {
return
}
// 6. 冷却去重:窗口外 push 立即执行并刷新 lastExec,窗口内 push 直接丢弃
lockKey := fmt.Sprintf("%s:%s", repoName, ref)
entryVal, _ := lastExecMap.LoadOrStore(lockKey, &debounceEntry{})
entry := entryVal.(*debounceEntry)
// 6. 入队等待 worker 按队列顺序消费
enqueueBuildTask(buildTask{
scriptPath: scriptPath,
repoName: repoName,
ref: ref,
commitID: commitID,
})
entry.mu.Lock()
now := time.Now()
if !entry.lastExec.IsZero() && now.Sub(entry.lastExec) < debounceDuration {
remainingSeconds := max(int((debounceDuration - now.Sub(entry.lastExec)).Seconds()), 0)
entry.mu.Unlock()
msg := fmt.Sprintf("3 分钟内频繁提交被拦截, 剩余冷却时间: %d 秒", remainingSeconds)
log.Printf("[DEBOUNCE] 跳过执行 [%s] %s\n", lockKey, msg)
c.JSON(http.StatusOK, gin.H{
"status": "debounced",
"message": msg,
"remaining_seconds": remainingSeconds,
})
return
}
entry.lastExec = now
entry.mu.Unlock()
log.Printf("[INFO] 开始执行脚本: %s (仓库: %s, 分支: %s, commit: %s)\n",
log.Printf("[QUEUED] 收到 push 入队 [%s] (仓库: %s, 分支: %s, commit: %s)\n",
scriptPath, repoName, ref, shortCommit(commitID))
go runScript(scriptPath, repoName, ref, commitID)
c.JSON(http.StatusOK, gin.H{
"status": "triggered",
"status": "queued",
"repository": repoName,
"ref": ref,
"script": scriptPath,