mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-11-16 14:54:23 +08:00
fix(i18n): use English runtime text and localize system UI
This commit is contained in:
@@ -209,7 +209,7 @@ func getPostgresOverview(gormDB *gorm.DB) DBOverviewResponse {
|
||||
func GetDBOverview(c *gin.Context) {
|
||||
gormDB := db.DB(c.Request.Context())
|
||||
if gormDB == nil {
|
||||
response.AbortInternal(c, "数据库未初始化")
|
||||
response.AbortInternal(c, "Database is not initialized")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -238,7 +238,7 @@ func GetDBOverview(c *gin.Context) {
|
||||
func ListDBTables(c *gin.Context) {
|
||||
gormDB := db.DB(c.Request.Context())
|
||||
if gormDB == nil {
|
||||
response.AbortInternal(c, "数据库未初始化")
|
||||
response.AbortInternal(c, "Database is not initialized")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -269,7 +269,7 @@ func GetDBTableData(c *gin.Context) {
|
||||
|
||||
gormDB := db.DB(c.Request.Context())
|
||||
if gormDB == nil {
|
||||
response.AbortInternal(c, "数据库未初始化")
|
||||
response.AbortInternal(c, "Database is not initialized")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -442,13 +442,13 @@ func ExecuteSQL(c *gin.Context) {
|
||||
|
||||
gormDB := db.DB(c.Request.Context())
|
||||
if gormDB == nil {
|
||||
response.AbortInternal(c, "数据库未初始化")
|
||||
response.AbortInternal(c, "Database is not initialized")
|
||||
return
|
||||
}
|
||||
|
||||
trimmedSQL := strings.TrimSpace(req.SQL)
|
||||
if trimmedSQL == "" {
|
||||
response.AbortBadRequest(c, "SQL 语句不能为空")
|
||||
response.AbortBadRequest(c, "SQL statement must not be empty")
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -7,9 +7,9 @@ package admin
|
||||
|
||||
// 管理后台错误消息常量
|
||||
const (
|
||||
AdminRequired = "未经授权访问"
|
||||
TokenAdminRequired = "该访问令牌没有管理员权限,无法访问管理端点" //nolint:gosec // false positive: this is an error message, not hardcoded credentials
|
||||
InvalidAuthSourceID = "认证源 ID 无效"
|
||||
InvalidCursorParam = "无效的 cursor 参数"
|
||||
InvalidTaskExecutionID = "无效的任务执行记录 ID"
|
||||
AdminRequired = "Unauthorized access"
|
||||
TokenAdminRequired = "This access token has no administrator privileges and cannot access admin endpoints" //nolint:gosec // false positive: this is an error message, not hardcoded credentials
|
||||
InvalidAuthSourceID = "invalid authentication source ID"
|
||||
InvalidCursorParam = "Invalid cursor parameter"
|
||||
InvalidTaskExecutionID = "Invalid task execution ID"
|
||||
)
|
||||
|
||||
@@ -165,7 +165,7 @@ func buildAccessLogFilter(ctx context.Context, c *gin.Context) (analyticsmodel.A
|
||||
if username != "" {
|
||||
userIDs, err := repository.ListUserIDsByUsernameContains(ctx, username)
|
||||
if err != nil {
|
||||
return filter, fmt.Errorf("查询用户信息失败: %w", err)
|
||||
return filter, fmt.Errorf("failed to query user information: %w", err)
|
||||
}
|
||||
filter.UserIDs = userIDs
|
||||
}
|
||||
@@ -246,8 +246,8 @@ func GetAccessLogs(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
store, err := logstore.Active(ctx)
|
||||
if err != nil {
|
||||
logger.ErrorF(ctx, "获取日志存储实例失败: %v", err)
|
||||
response.AbortWithError(c, http.StatusBadRequest, "日志存储未启用,无法检索访问日志")
|
||||
logger.ErrorF(ctx, "Failed to get log storage instance: %v", err)
|
||||
response.AbortWithError(c, http.StatusBadRequest, "Log storage is disabled; access logs cannot be retrieved")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -348,8 +348,8 @@ func GetLogsAnalytics(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
store, err := logstore.Active(ctx)
|
||||
if err != nil {
|
||||
logger.ErrorF(ctx, "获取日志存储实例失败: %v", err)
|
||||
response.AbortWithError(c, http.StatusBadRequest, "日志存储未启用,无法获取分析数据")
|
||||
logger.ErrorF(ctx, "Failed to get log storage instance: %v", err)
|
||||
response.AbortWithError(c, http.StatusBadRequest, "Log storage is disabled; analytics are unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -357,7 +357,7 @@ func GetLogsAnalytics(c *gin.Context) {
|
||||
|
||||
trendPoints, err := store.UserAccessLogs.GetDailyTrend(ctx, analyticsDays)
|
||||
if err != nil {
|
||||
response.AbortWithError(c, http.StatusInternalServerError, "查询访问趋势失败: "+err.Error())
|
||||
response.AbortWithError(c, http.StatusInternalServerError, "Failed to query access trends: "+err.Error())
|
||||
return
|
||||
}
|
||||
trendList := make([]trendItem, len(trendPoints))
|
||||
@@ -370,7 +370,7 @@ func GetLogsAnalytics(c *gin.Context) {
|
||||
|
||||
browserPoints, err := store.UserAccessLogs.GetBrowserDistribution(ctx, startTime)
|
||||
if err != nil {
|
||||
response.AbortWithError(c, http.StatusInternalServerError, "查询浏览器分布失败: "+err.Error())
|
||||
response.AbortWithError(c, http.StatusInternalServerError, "Failed to query browser distribution: "+err.Error())
|
||||
return
|
||||
}
|
||||
browserList := make([]browserItem, len(browserPoints))
|
||||
@@ -383,7 +383,7 @@ func GetLogsAnalytics(c *gin.Context) {
|
||||
|
||||
topUserPoints, err := store.UserAccessLogs.GetTopActiveUsers(ctx, startTime, topActiveLimit)
|
||||
if err != nil {
|
||||
response.AbortWithError(c, http.StatusInternalServerError, "查询活跃用户失败: "+err.Error())
|
||||
response.AbortWithError(c, http.StatusInternalServerError, "Failed to query active users: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -221,9 +221,9 @@ func TestChannel(c *gin.Context) {
|
||||
default:
|
||||
config = pkgpush.Config{Channel: channelCustom, URL: url}
|
||||
customPushReq := CustomPushRequest{
|
||||
Title: "通道测试通知",
|
||||
Content: "这是一条来自系统的消息通道连通性测试消息。",
|
||||
Description: "系统通道测试",
|
||||
Title: "Channel test notification",
|
||||
Content: "This is a system notification channel connectivity test.",
|
||||
Description: "System channel test",
|
||||
URL: "https://example.com",
|
||||
To: req.Target,
|
||||
}
|
||||
@@ -235,8 +235,8 @@ func TestChannel(c *gin.Context) {
|
||||
Config: config,
|
||||
Target: req.Target,
|
||||
Body: NotificationMessage{
|
||||
Title: "通道测试通知",
|
||||
Content: "这是一条来自系统的消息通道连通性测试消息。",
|
||||
Title: "Channel test notification",
|
||||
Content: "This is a system notification channel connectivity test.",
|
||||
Level: defaultLevelInfo,
|
||||
},
|
||||
Template: renderedJSON,
|
||||
|
||||
@@ -81,24 +81,24 @@ func init() {
|
||||
// Register custom webhook channel
|
||||
RegisterChannelDefinition(Definition{
|
||||
Type: channelCustom,
|
||||
Name: "自定义消息通道",
|
||||
Description: "使用自定义 HTTP POST 请求向外部 Webhook 发送数据。",
|
||||
Name: "Custom notification channel",
|
||||
Description: "Send data to an external webhook using a custom HTTP POST request.",
|
||||
Fields: []Field{
|
||||
{
|
||||
Key: KeyURL,
|
||||
Label: "请求地址",
|
||||
Label: "Request URL",
|
||||
Type: TypeText,
|
||||
Required: true,
|
||||
Placeholder: "在此填写完整的请求地址,必须使用 HTTPS 协议",
|
||||
Description: "接口请求的完整 HTTPS URL,例如 https://api.example.com/webhook",
|
||||
Placeholder: "Enter the complete request URL using HTTPS",
|
||||
Description: "Complete HTTPS endpoint URL, for example https://api.example.com/webhook",
|
||||
},
|
||||
{
|
||||
Key: KeyOther,
|
||||
Label: "请求体 (JSON)",
|
||||
Label: "Request body (JSON)",
|
||||
Type: TypeTextarea,
|
||||
Required: true,
|
||||
Placeholder: "在此输入请求体,支持模板变量,必须为合法的 JSON 格式",
|
||||
Description: "可使用的变量:$title, $description, $content, $url, $to。例如 {\"text\": \"$content\"}",
|
||||
Placeholder: "Enter a valid JSON request body; template variables are supported",
|
||||
Description: `Available variables: $title, $description, $content, $url, $to. Example: {"text": "$content"}`,
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -106,33 +106,33 @@ func init() {
|
||||
// Register Lark robot channel
|
||||
RegisterChannelDefinition(Definition{
|
||||
Type: channelLark,
|
||||
Name: "飞书群机器人",
|
||||
Description: "配置飞书群自定义机器人的 Webhook 接口投递。",
|
||||
Name: "Feishu group bot",
|
||||
Description: "Deliver notifications through a Feishu group bot webhook.",
|
||||
Fields: []Field{
|
||||
{
|
||||
Key: KeyURL,
|
||||
Label: "Webhook 地址",
|
||||
Label: "Webhook URL",
|
||||
Type: TypeText,
|
||||
Required: true,
|
||||
Placeholder: "https://open.feishu.cn/open-apis/bot/v2/hook/YOUR_TOKEN",
|
||||
Description: "从飞书群机器人设置中复制 of Webhook URL",
|
||||
Description: "Copy the webhook URL from the Feishu group bot settings",
|
||||
// Note: using 'of' was in feishu.go, let's keep original wording or fix it
|
||||
},
|
||||
{
|
||||
Key: KeyToken,
|
||||
Label: "签名校验密钥 (Secret) (可选)",
|
||||
Label: "Signing secret (optional)",
|
||||
Type: TypeText,
|
||||
Required: false,
|
||||
Placeholder: "可选,若机器人启用了安全设置中的签名校验,请在此输入",
|
||||
Description: "飞书群机器人安全设置中的签名校验 Key",
|
||||
Placeholder: "Enter the secret if signature verification is enabled for the bot",
|
||||
Description: "Signature verification key from the Feishu group bot security settings",
|
||||
},
|
||||
{
|
||||
Key: KeyOther,
|
||||
Label: "自定义卡片 JSON 模版 (可选)",
|
||||
Label: "Custom card JSON template (optional)",
|
||||
Type: TypeTextarea,
|
||||
Required: false,
|
||||
Placeholder: "可选,留空则默认使用系统内置的精美互动卡片",
|
||||
Description: "若填写,必须是合法的飞书卡片 JSON 格式",
|
||||
Placeholder: "Leave empty to use the built-in interactive card",
|
||||
Description: "If specified, this must be valid Feishu card JSON",
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -140,32 +140,32 @@ func init() {
|
||||
// Register Telegram channel
|
||||
RegisterChannelDefinition(Definition{
|
||||
Type: channelTelegram,
|
||||
Name: "Telegram 机器人",
|
||||
Description: "配置 Telegram 机器人推送消息。",
|
||||
Name: "Telegram bot",
|
||||
Description: "Configure Telegram bot notifications.",
|
||||
Fields: []Field{
|
||||
{
|
||||
Key: KeyURL,
|
||||
Label: "API 基础地址 (可选)",
|
||||
Label: "API base URL (optional)",
|
||||
Type: TypeText,
|
||||
Required: false,
|
||||
Placeholder: "https://api.telegram.org",
|
||||
Description: "接口请求的 HTTPS 基础地址,留空默认为 https://api.telegram.org",
|
||||
Description: "HTTPS API base URL; defaults to https://api.telegram.org",
|
||||
},
|
||||
{
|
||||
Key: KeyToken,
|
||||
Label: "机器人 Token (Bot Token)",
|
||||
Label: "Bot token",
|
||||
Type: TypePassword,
|
||||
Required: true,
|
||||
Placeholder: "在此输入 Telegram 机器人的 Bot Token",
|
||||
Description: "通过 BotFather 申请到的机器人 Access Token",
|
||||
Placeholder: "Enter the Telegram bot token",
|
||||
Description: "Bot access token issued by BotFather",
|
||||
},
|
||||
{
|
||||
Key: KeyOther,
|
||||
Label: "默认会话 ID (Chat ID) (可选)",
|
||||
Label: "Default chat ID (optional)",
|
||||
Type: TypeText,
|
||||
Required: false,
|
||||
Placeholder: "例如 -100123456789 或 @channel_name",
|
||||
Description: "默认的消息接收 Chat ID。如果通知事件中未配置 targets,将推送到此 ID",
|
||||
Placeholder: "For example -100123456789 or @channel_name",
|
||||
Description: "Default recipient chat ID, used when the notification event has no targets",
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -173,8 +173,8 @@ func init() {
|
||||
// Register Email channel
|
||||
RegisterChannelDefinition(Definition{
|
||||
Type: channelEmail,
|
||||
Name: "邮件推送通道",
|
||||
Description: "邮件推送通道直接使用系统全局 SMTP 设置进行发送,无需在此填写服务器配置。",
|
||||
Name: "Email notification channel",
|
||||
Description: "Email notifications use the global SMTP settings; no server configuration is required here.",
|
||||
Fields: []Field{},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -15,13 +15,13 @@ import (
|
||||
// AdminLogin is the metadata definition for the admin login event.
|
||||
var AdminLogin = push.EventMetadata{
|
||||
Key: "admin_login",
|
||||
Name: "管理员登录",
|
||||
Name: "Administrator login",
|
||||
DefaultTemplate: push.NotificationMessage{
|
||||
Title: "管理员登录提醒",
|
||||
Content: "管理员 {{user.username}} 于 {{time}} 从 IP {{ip}} 登录系统。",
|
||||
Title: "Administrator login notification",
|
||||
Content: "Administrator {{user.username}} signed in at {{time}} from IP {{ip}}.",
|
||||
Level: "INFO",
|
||||
},
|
||||
Description: "当管理员成功登录系统时触发此通知",
|
||||
Description: "Triggered when an administrator signs in successfully",
|
||||
}
|
||||
|
||||
func handleAdminLogin(ctx context.Context, event listener.AdminLoggedIn) {
|
||||
|
||||
@@ -138,7 +138,7 @@ func TestAdminLoginPushIntegration(t *testing.T) {
|
||||
|
||||
assert.Equal(t, AdminLogin.Key, payload.EventKey)
|
||||
assert.Equal(t, "ops_team", payload.Target)
|
||||
assert.Equal(t, "管理员登录提醒", payload.Body.Title)
|
||||
assert.Equal(t, "Administrator login notification", payload.Body.Title)
|
||||
assert.Contains(t, payload.Body.Content, "super_admin")
|
||||
assert.Contains(t, payload.Body.Content, "203.0.113.42")
|
||||
})
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package push
|
||||
|
||||
import (
|
||||
"github.com/Rain-kl/Wavelet/internal/infra/task"
|
||||
"github.com/Rain-kl/Wavelet/internal/model"
|
||||
"github.com/Rain-kl/Wavelet/pkg/i18n"
|
||||
)
|
||||
|
||||
func localizeEventMetadata(locale string, meta EventMetadata) EventMetadata {
|
||||
meta.Name = i18n.Translate(locale, meta.Name)
|
||||
meta.Description = i18n.Translate(locale, meta.Description)
|
||||
meta.DefaultTemplate.Title = i18n.Translate(locale, meta.DefaultTemplate.Title)
|
||||
meta.DefaultTemplate.Content = i18n.Translate(locale, meta.DefaultTemplate.Content)
|
||||
return meta
|
||||
}
|
||||
|
||||
func localizePushEvent(locale string, event model.PushEvent) model.PushEvent {
|
||||
if meta, found := findBuiltInEvent(event.EventKey); found {
|
||||
if event.Name == meta.Name || i18n.Translate("en", event.Name) == meta.Name {
|
||||
event.Name = i18n.Translate(locale, meta.Name)
|
||||
}
|
||||
} else if meta := task.GetTaskMetaByAsynqTask(event.TaskType); meta != nil {
|
||||
prefix := "Task completed: "
|
||||
english := prefix + meta.Name
|
||||
chinese := i18n.Translate("zh-CN", prefix) + i18n.Translate("zh-CN", meta.Name)
|
||||
if event.Name == english || event.Name == chinese {
|
||||
event.Name = i18n.Translate(locale, prefix) + i18n.Translate(locale, meta.Name)
|
||||
}
|
||||
}
|
||||
// Templates and targets are administrator-owned data, even when they happen
|
||||
// to match a built-in message. Never rewrite them during presentation.
|
||||
return event
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package push
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/Rain-kl/Wavelet/internal/model"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestLocalizeEventMetadataPreservesTemplatesAndRegistry(t *testing.T) {
|
||||
source := EventMetadata{Name: "Administrator login", DefaultTemplate: NotificationMessage{Title: "Administrator login notification"}}
|
||||
localized := localizeEventMetadata("zh-CN", source)
|
||||
assert.Equal(t, "管理员登录", localized.Name)
|
||||
assert.Equal(t, "管理员登录提醒", localized.DefaultTemplate.Title)
|
||||
assert.Equal(t, "Administrator login", source.Name)
|
||||
assert.Equal(t, "Administrator login notification", source.DefaultTemplate.Title)
|
||||
|
||||
event := model.PushEvent{Name: "自定义事件", Template: `{"title":"管理员登录提醒"}`, Targets: []string{"系统"}}
|
||||
assert.Equal(t, event, localizePushEvent("en", event))
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"github.com/Rain-kl/Wavelet/internal/infra/task"
|
||||
"github.com/Rain-kl/Wavelet/internal/model"
|
||||
"github.com/Rain-kl/Wavelet/internal/repository"
|
||||
"github.com/Rain-kl/Wavelet/pkg/i18n"
|
||||
pkgpush "github.com/Rain-kl/Wavelet/pkg/push"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
@@ -278,7 +279,7 @@ func recordPushHistory(ctx context.Context, req SendPayload, status, errMsg stri
|
||||
content := req.Body.Content
|
||||
level := req.Body.Level
|
||||
if title == "" {
|
||||
title = "系统通知"
|
||||
title = "System notification"
|
||||
}
|
||||
if level == "" {
|
||||
level = defaultLevelInfo
|
||||
@@ -331,7 +332,7 @@ func resolveTargetUser(ctx context.Context, resolved string, _ string) (model.Us
|
||||
}
|
||||
|
||||
func resolveSystemTarget(ctx context.Context, resolved string, channel string) (string, bool) {
|
||||
if resolved != "系统" && resolved != "system" && resolved != "0" {
|
||||
if i18n.Translate("en", resolved) != "System" && resolved != "system" && resolved != "0" {
|
||||
return "", false
|
||||
}
|
||||
adminUser, err := repository.GetFirstAdminUser(ctx)
|
||||
@@ -383,10 +384,10 @@ func getEventInfo(req CreateEventRequest) (string, string, []byte, error) {
|
||||
return "", "", nil, errors.New("unsupported task type")
|
||||
}
|
||||
eventKey := "task_completed:" + req.TaskType
|
||||
eventName := "任务完成: " + meta.Name
|
||||
eventName := "Task completed: " + meta.Name
|
||||
defaultTemplate := NotificationMessage{
|
||||
Title: "任务完成: " + meta.Name,
|
||||
Content: "异步任务 {{task_name}} (ID: {{task_id}}) 已完成。状态: {{task_status}},耗时: {{task_duration}} ms。",
|
||||
Title: "Task completed: " + meta.Name,
|
||||
Content: "Asynchronous task {{task_name}} (ID: {{task_id}}) completed. Status: {{task_status}}; duration: {{task_duration}} ms.",
|
||||
Level: defaultLevelInfo,
|
||||
}
|
||||
defaultTemplateBytes, err := json.Marshal(defaultTemplate)
|
||||
|
||||
@@ -312,7 +312,7 @@ func TestPushHandler(t *testing.T) {
|
||||
t.Run("execute task successfully", func(t *testing.T) {
|
||||
res, execErr := handler.Execute(context.Background(), payloadBytes)
|
||||
require.NoError(t, execErr)
|
||||
assert.Contains(t, res.Message, "推送成功")
|
||||
assert.Contains(t, res.Message, "Notification sent")
|
||||
|
||||
// Verify mock pusher received flattened variables
|
||||
mPusher.mu.Lock()
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strconv"
|
||||
|
||||
"github.com/Rain-kl/Wavelet/internal/model"
|
||||
@@ -54,6 +55,9 @@ func ListEvents(c *gin.Context) {
|
||||
response.AbortInternal(c, err.Error())
|
||||
return
|
||||
}
|
||||
for index := range events {
|
||||
events[index] = localizePushEvent(response.Locale(c), events[index])
|
||||
}
|
||||
c.JSON(http.StatusOK, response.OK(events))
|
||||
}
|
||||
|
||||
@@ -85,7 +89,11 @@ func findBuiltInEvent(key string) (EventMetadata, bool) {
|
||||
// @Success 200 {object} response.Any{data=[]EventMetadata} "内置通知事件列表"
|
||||
// @Router /api/v1/admin/push/events/builtin [get]
|
||||
func ListBuiltInEvents(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, response.OK(BuiltInEvents))
|
||||
metas := slices.Clone(BuiltInEvents)
|
||||
for index := range metas {
|
||||
metas[index] = localizeEventMetadata(response.Locale(c), metas[index])
|
||||
}
|
||||
c.JSON(http.StatusOK, response.OK(metas))
|
||||
}
|
||||
|
||||
// CreateEvent 创建通知事件
|
||||
@@ -110,7 +118,7 @@ func CreateEvent(c *gin.Context) {
|
||||
response.AbortBadRequest(c, err.Error())
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, response.OK(event))
|
||||
c.JSON(http.StatusOK, response.OK(localizePushEvent(response.Locale(c), event)))
|
||||
}
|
||||
|
||||
// DeleteEvent 删除通知事件配置
|
||||
@@ -280,8 +288,8 @@ func TestPush(c *gin.Context) {
|
||||
applySMTPFallbackToPushConfig(c.Request.Context(), &req.Config)
|
||||
|
||||
testBody := map[string]any{
|
||||
keyTitle: "测试通道推送",
|
||||
keyContent: "当您收到这条消息,说明当前渠道连通性测试通过。",
|
||||
keyTitle: "Notification channel test",
|
||||
keyContent: "Receiving this message confirms that the notification channel connectivity test succeeded.",
|
||||
keyLevel: defaultLevelInfo,
|
||||
}
|
||||
if _, err := pusher.Send(c.Request.Context(), req.Config, req.Target, testBody, "", nil); err != nil {
|
||||
|
||||
@@ -67,7 +67,7 @@ func handleTaskCompleted(ctx context.Context, execution *model.TaskExecution, re
|
||||
meta := EventMetadata{
|
||||
Key: event.EventKey,
|
||||
Name: event.Name,
|
||||
Description: "异步任务执行完毕触发的自动通知",
|
||||
Description: "Automatic notification triggered when an asynchronous task finishes",
|
||||
}
|
||||
DefaultTrigger.Trigger(ctx, meta, body)
|
||||
}
|
||||
|
||||
@@ -25,8 +25,8 @@ const (
|
||||
var SendNotificationMeta = task.TaskMeta{
|
||||
Type: TaskTypeSendNotification,
|
||||
AsynqTask: SendNotificationTask,
|
||||
Name: "推送通知",
|
||||
Description: "异步执行系统通知的多渠道派发与推送",
|
||||
Name: "Send notification",
|
||||
Description: "Dispatch system notifications asynchronously across multiple channels",
|
||||
SupportsTime: false,
|
||||
MaxRetry: task.DefaultMaxRetry,
|
||||
Queue: task.QueueDefault,
|
||||
@@ -34,14 +34,14 @@ var SendNotificationMeta = task.TaskMeta{
|
||||
Params: []task.TaskParam{
|
||||
{
|
||||
Name: "event_key",
|
||||
Label: "事件标识",
|
||||
Label: "Event key",
|
||||
Type: "string",
|
||||
Required: true,
|
||||
Placeholder: "admin_login",
|
||||
},
|
||||
{
|
||||
Name: "target",
|
||||
Label: "目标接收者",
|
||||
Label: "Recipient",
|
||||
Type: "string",
|
||||
Required: false,
|
||||
},
|
||||
@@ -75,16 +75,16 @@ func (h *PushHandler) ValidatePayload(payload []byte) ([]byte, error) {
|
||||
func (h *PushHandler) Execute(ctx context.Context, payload []byte) (*task.TaskResult, error) {
|
||||
var req SendPayload
|
||||
if err := json.Unmarshal(payload, &req); err != nil {
|
||||
task.AppendLog(ctx, "解析推送参数失败: %v", err)
|
||||
task.AppendLog(ctx, "Failed to parse notification parameters: %v", err)
|
||||
return nil, fmt.Errorf("parse payload failed: %w", err)
|
||||
}
|
||||
|
||||
task.AppendLog(ctx, "开始推送通知: 事件 = %s, 渠道 = %s, 接收目标 = %s", req.EventKey, req.Config.Channel, req.Target)
|
||||
task.AppendLog(ctx, "Starting notification: event = %s, channel = %s, recipient = %s", req.EventKey, req.Config.Channel, req.Target)
|
||||
|
||||
pusher, err := push.GetPusher(req.Config.Channel)
|
||||
if err != nil {
|
||||
errWrap := fmt.Errorf("get pusher failed: %w", err)
|
||||
task.AppendLog(ctx, "推送失败: %v", errWrap)
|
||||
task.AppendLog(ctx, "Notification failed: %v", errWrap)
|
||||
if task.IsFinalAttempt(ctx) {
|
||||
h.recordHistory(ctx, req, "failed", errWrap.Error())
|
||||
}
|
||||
@@ -99,9 +99,9 @@ func (h *PushHandler) Execute(ctx context.Context, payload []byte) (*task.TaskRe
|
||||
content := req.Body.Content
|
||||
|
||||
if err != nil {
|
||||
task.AppendLog(ctx, "消息推送失败 (标题: %s): %v", title, err)
|
||||
task.AppendLog(ctx, "Failed to send notification (title: %s): %v", title, err)
|
||||
if upstreamResp != "" {
|
||||
task.AppendLog(ctx, "上游返回: %s", upstreamResp)
|
||||
task.AppendLog(ctx, "Upstream response: %s", upstreamResp)
|
||||
}
|
||||
if task.IsFinalAttempt(ctx) {
|
||||
h.recordHistory(ctx, req, "failed", err.Error())
|
||||
@@ -109,19 +109,19 @@ func (h *PushHandler) Execute(ctx context.Context, payload []byte) (*task.TaskRe
|
||||
return nil, fmt.Errorf("pusher.Send failed: %w", err)
|
||||
}
|
||||
|
||||
task.AppendLog(ctx, "消息推送成功 (标题: %s, 内容摘要: %s)", title, content)
|
||||
task.AppendLog(ctx, "Notification sent (title: %s, content summary: %s)", title, content)
|
||||
if upstreamResp != "" {
|
||||
task.AppendLog(ctx, "上游返回: %s", upstreamResp)
|
||||
task.AppendLog(ctx, "Upstream response: %s", upstreamResp)
|
||||
}
|
||||
h.recordHistory(ctx, req, "success", "")
|
||||
|
||||
return &task.TaskResult{
|
||||
Message: fmt.Sprintf("推送成功: [%s] -> %s", req.Config.Channel, req.Target),
|
||||
Message: fmt.Sprintf("Notification sent: [%s] -> %s", req.Config.Channel, req.Target),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *PushHandler) recordHistory(ctx context.Context, req SendPayload, status string, errMsg string) {
|
||||
if dbErr := recordPushHistory(ctx, req, status, errMsg); dbErr != nil {
|
||||
task.AppendLog(ctx, "写入推送历史审计记录失败: %v", dbErr)
|
||||
task.AppendLog(ctx, "Failed to write notification audit history: %v", dbErr)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,16 +55,16 @@ func GetLogDatabaseStatus(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
store, err := logstore.Active(ctx)
|
||||
if err != nil {
|
||||
logger.ErrorF(ctx, "获取日志存储实例失败: %v", err)
|
||||
response.AbortInternal(c, "日志存储初始化失败")
|
||||
logger.ErrorF(ctx, "Failed to get log storage instance: %v", err)
|
||||
response.AbortInternal(c, "Failed to initialize log storage")
|
||||
return
|
||||
}
|
||||
|
||||
// 分支判定复用同一 store 实例的 ActiveDatabase,避免与 Active 解析之间出现 TOCTOU。
|
||||
activeDB, err := store.Status.ActiveDatabase(ctx)
|
||||
if err != nil {
|
||||
logger.ErrorF(ctx, "获取日志库状态失败: %v", err)
|
||||
response.AbortInternal(c, "获取日志库状态失败")
|
||||
logger.ErrorF(ctx, "Failed to get log database status: %v", err)
|
||||
response.AbortInternal(c, "Failed to get log database status")
|
||||
return
|
||||
}
|
||||
migration := "idle"
|
||||
@@ -86,7 +86,7 @@ func GetLogDatabaseStatus(c *gin.Context) {
|
||||
if activeDB == logDBNameClickHouse {
|
||||
stats, err := store.Status.ClickHouseOperationalStats(ctx)
|
||||
if err != nil {
|
||||
logger.ErrorF(ctx, "获取 ClickHouse 运行指标失败: %v", err)
|
||||
logger.ErrorF(ctx, "Failed to get ClickHouse runtime metrics: %v", err)
|
||||
} else {
|
||||
stats.BatchWriters = collectBatchWriterStats()
|
||||
out.ClickHouse = stats
|
||||
@@ -101,7 +101,7 @@ func retentionOr(ctx context.Context, key string) int {
|
||||
v, err := repository.GetIntByKey(ctx, key)
|
||||
if err != nil {
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
logger.ErrorF(ctx, "读取日志保留天数配置失败 key=%s: %v", key, err)
|
||||
logger.ErrorF(ctx, "Failed to read log retention configuration key=%s: %v", key, err)
|
||||
}
|
||||
return defaultLogRetentionDays
|
||||
}
|
||||
|
||||
@@ -120,16 +120,16 @@ func formatDuration(d time.Duration) string {
|
||||
|
||||
var res string
|
||||
if days > 0 {
|
||||
res += fmt.Sprintf("%d天", days)
|
||||
res += fmt.Sprintf("%d days", days)
|
||||
}
|
||||
if hours > 0 {
|
||||
res += fmt.Sprintf("%d小时", hours)
|
||||
res += fmt.Sprintf("%d hours", hours)
|
||||
}
|
||||
if minutes > 0 {
|
||||
res += fmt.Sprintf("%d分钟", minutes)
|
||||
res += fmt.Sprintf("%d minutes", minutes)
|
||||
}
|
||||
if seconds > 0 || res == "" {
|
||||
res += fmt.Sprintf("%d秒钟", seconds)
|
||||
res += fmt.Sprintf("%d seconds", seconds)
|
||||
}
|
||||
return res
|
||||
}
|
||||
@@ -156,9 +156,9 @@ func GetSystemStatus(c *gin.Context) {
|
||||
case m.LastGC > 0 && m.LastGC <= math.MaxInt64:
|
||||
lastGCTime = formatDuration(time.Since(time.Unix(0, int64(m.LastGC))))
|
||||
case m.LastGC > 0:
|
||||
lastGCTime = "未知"
|
||||
lastGCTime = "Unknown"
|
||||
default:
|
||||
lastGCTime = "无"
|
||||
lastGCTime = "None"
|
||||
}
|
||||
|
||||
var lastPause string
|
||||
@@ -292,7 +292,7 @@ func exportSQLite(c *gin.Context) {
|
||||
dir, err := os.MkdirTemp("", "openflare-db-export-*")
|
||||
if err != nil {
|
||||
logger.ErrorF(c.Request.Context(), "[db-export] create temporary directory failed: %v", err)
|
||||
response.AbortInternal(c, "无法创建数据库导出文件")
|
||||
response.AbortInternal(c, "Unable to create database export file")
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
@@ -303,13 +303,13 @@ func exportSQLite(c *gin.Context) {
|
||||
path := filepath.Join(dir, "openflare.db")
|
||||
if err := repository.ExportSQLiteSnapshot(c.Request.Context(), path); err != nil {
|
||||
logger.ErrorF(c.Request.Context(), "[db-export] create SQLite snapshot failed: %v", err)
|
||||
response.AbortInternal(c, "无法导出数据库")
|
||||
response.AbortInternal(c, "Unable to export database")
|
||||
return
|
||||
}
|
||||
|
||||
f, err := os.Open(path) //nolint:gosec // path is generated in a private temporary directory, not from user input
|
||||
if err != nil {
|
||||
response.AbortInternal(c, "无法打开数据库文件: "+err.Error())
|
||||
response.AbortInternal(c, "Unable to open database file: "+err.Error())
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
@@ -320,7 +320,7 @@ func exportSQLite(c *gin.Context) {
|
||||
|
||||
fi, err := f.Stat()
|
||||
if err != nil {
|
||||
response.AbortInternal(c, "无法读取数据库文件信息: "+err.Error())
|
||||
response.AbortInternal(c, "Unable to read database file information: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
@@ -338,7 +338,7 @@ func exportPostgres(c *gin.Context) {
|
||||
// 检查 pg_dump 是否可用
|
||||
pgDumpPath, err := exec.LookPath("pg_dump")
|
||||
if err != nil {
|
||||
response.AbortInternal(c, "pg_dump 不可用,请确保服务器已安装 PostgreSQL 客户端工具")
|
||||
response.AbortInternal(c, "pg_dump is unavailable; install the PostgreSQL client tools on the server")
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -7,9 +7,9 @@ package system_config
|
||||
|
||||
// 系统配置错误消息常量
|
||||
const (
|
||||
SystemConfigNotFound = "系统配置不存在"
|
||||
ConfigKeyRequired = "配置键不能为空"
|
||||
ConfigValueRequired = "配置值不能为空"
|
||||
ConfigKeyExists = "配置键已存在"
|
||||
StorageDriverSwitchRequiresMigration = "存在存量文件,请通过存储迁移任务切换存储引擎"
|
||||
SystemConfigNotFound = "System configuration was not found"
|
||||
ConfigKeyRequired = "Configuration key must not be empty"
|
||||
ConfigValueRequired = "Configuration value must not be empty"
|
||||
ConfigKeyExists = "configuration key already exists"
|
||||
StorageDriverSwitchRequiresMigration = "existing files were found; use the storage migration task to switch storage backends"
|
||||
)
|
||||
|
||||
@@ -43,7 +43,7 @@ func createSystemConfig(ctx context.Context, req CreateSystemConfigRequest) erro
|
||||
|
||||
invalidateSystemConfigCaches(ctx, req.Key)
|
||||
if err := repository.InvalidateVisibleSystemConfigsCache(ctx); err != nil {
|
||||
logger.WarnF(ctx, "清理公共配置列表缓存失败: %v", err)
|
||||
logger.WarnF(ctx, "Failed to clear public configuration list cache: %v", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -71,7 +71,7 @@ func updateSystemConfig(ctx context.Context, key string, req UpdateSystemConfigR
|
||||
|
||||
validatedVal, err := validateAndMergeStorageConfig(ctx, req.Value, config.Value)
|
||||
if err != nil {
|
||||
return err
|
||||
return &storageConfigValidationError{err}
|
||||
}
|
||||
req.Value = validatedVal
|
||||
}
|
||||
@@ -123,9 +123,9 @@ func resolveStorageMigrationTasksOnDirectDriverUpdate(
|
||||
if err := repository.MarkFailedTaskExecutionsSucceededTx(
|
||||
tx,
|
||||
"storage:migrate",
|
||||
"存储配置直接更新,故障迁移任务自动标记为已解决",
|
||||
"Storage configuration updated directly; failed migration task marked as resolved",
|
||||
time.Now(),
|
||||
); err != nil {
|
||||
logger.ErrorF(ctx, "自动更新迁移任务状态失败: %v", err)
|
||||
logger.ErrorF(ctx, "Failed to automatically update migration task status: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
@@ -28,7 +27,7 @@ import (
|
||||
const maskedConfigValue = "******"
|
||||
|
||||
// protectedConfigKeyMessage 命中受保护 key 时返回给管理员的业务错误文案。
|
||||
const protectedConfigKeyMessage = "该配置项由系统任务管理,禁止手动修改"
|
||||
const protectedConfigKeyMessage = "this configuration is managed by system tasks and cannot be changed manually"
|
||||
|
||||
// protectedConfigKeys 仅允许内部(迁移任务/bootstrap)写入的 key。
|
||||
var protectedConfigKeys = map[string]bool{
|
||||
@@ -198,7 +197,7 @@ func UpdateSystemConfig(c *gin.Context) {
|
||||
|
||||
func invalidateSystemConfigCaches(ctx context.Context, key string) {
|
||||
if err := repository.InvalidateSystemConfigCache(ctx, key); err != nil {
|
||||
logger.WarnF(ctx, "清理系统配置缓存失败: %v", err)
|
||||
logger.WarnF(ctx, "Failed to clear system configuration cache: %v", err)
|
||||
}
|
||||
if cap.IsRuntimeConfigKey(key) {
|
||||
cap.InvalidateRuntimeSettings()
|
||||
@@ -220,7 +219,7 @@ func invalidateCachesAfterConfigUpdate(ctx context.Context, key string) {
|
||||
}
|
||||
|
||||
if err := repository.InvalidateVisibleSystemConfigsCache(ctx); err != nil {
|
||||
logger.WarnF(ctx, "清理公共配置列表缓存失败: %v", err)
|
||||
logger.WarnF(ctx, "Failed to clear public configuration list cache: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -289,15 +288,13 @@ func TestSMTP(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, response.OK(resp))
|
||||
}
|
||||
|
||||
type storageConfigValidationError struct{ error }
|
||||
|
||||
func (e *storageConfigValidationError) Unwrap() error { return e.error }
|
||||
|
||||
func isStorageConfigValidationError(err error) bool {
|
||||
msg := err.Error()
|
||||
return msg == StorageDriverSwitchRequiresMigration ||
|
||||
strings.HasPrefix(msg, "解析") ||
|
||||
strings.HasPrefix(msg, "验证") ||
|
||||
strings.HasPrefix(msg, "初始化测试") ||
|
||||
strings.HasPrefix(msg, "存储连通性") ||
|
||||
strings.HasPrefix(msg, "序列化") ||
|
||||
strings.HasPrefix(msg, "检查存量文件")
|
||||
var validationErr *storageConfigValidationError
|
||||
return errors.As(err, &validationErr)
|
||||
}
|
||||
|
||||
func maskSensitiveConfig(key, value string) string {
|
||||
@@ -324,12 +321,12 @@ func maskSensitiveConfig(key, value string) string {
|
||||
func validateAndMergeStorageConfig(ctx context.Context, value string, currentConfig string) (string, error) {
|
||||
var currentCfg objectstore.Config
|
||||
if err := json.Unmarshal([]byte(currentConfig), ¤tCfg); err != nil {
|
||||
return "", fmt.Errorf("解析当前存储配置失败: %w", err)
|
||||
return "", fmt.Errorf("failed to parse current storage configuration: %w", err)
|
||||
}
|
||||
|
||||
var newCfg objectstore.Config
|
||||
if err := json.Unmarshal([]byte(value), &newCfg); err != nil {
|
||||
return "", fmt.Errorf("解析目标存储配置失败: %w", err)
|
||||
return "", fmt.Errorf("failed to parse target storage configuration: %w", err)
|
||||
}
|
||||
|
||||
// 合并被掩码屏蔽的敏感信息,获取完整的真实配置
|
||||
@@ -341,7 +338,7 @@ func validateAndMergeStorageConfig(ctx context.Context, value string, currentCon
|
||||
// 序列化为最终保存的真实明文配置,防止保存屏蔽的 ****** 字符
|
||||
unmaskedVal, err := json.Marshal(targetCfg)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("序列化存储配置失败: %w", err)
|
||||
return "", fmt.Errorf("failed to serialize storage configuration: %w", err)
|
||||
}
|
||||
|
||||
return string(unmaskedVal), nil
|
||||
@@ -351,13 +348,13 @@ func validateMergedStorageConfig(ctx context.Context, currentCfg, newCfg, target
|
||||
if newCfg.Driver != "" && newCfg.Driver != currentCfg.Driver {
|
||||
uploadCount, err := repository.CountActiveUploads(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("检查存量文件失败: %w", err)
|
||||
return fmt.Errorf("failed to check existing files: %w", err)
|
||||
}
|
||||
if uploadCount > 0 {
|
||||
return errors.New(StorageDriverSwitchRequiresMigration)
|
||||
}
|
||||
if err := validateDriverConfig(targetCfg, newCfg.Driver); err != nil {
|
||||
return fmt.Errorf("验证目标存储配置参数失败: %w", err)
|
||||
return fmt.Errorf("failed to validate target storage parameters: %w", err)
|
||||
}
|
||||
pendingCfg := targetCfg
|
||||
pendingCfg.Driver = newCfg.Driver
|
||||
@@ -365,7 +362,7 @@ func validateMergedStorageConfig(ctx context.Context, currentCfg, newCfg, target
|
||||
}
|
||||
|
||||
if err := objectstore.ValidateConfig(targetCfg); err != nil {
|
||||
return fmt.Errorf("验证存储配置参数失败: %w", err)
|
||||
return fmt.Errorf("failed to validate storage parameters: %w", err)
|
||||
}
|
||||
return testStorageBackend(ctx, targetCfg, targetCfg.Driver)
|
||||
}
|
||||
@@ -378,10 +375,10 @@ func validateDriverConfig(cfg objectstore.Config, driver objectstore.Driver) err
|
||||
func testStorageBackend(ctx context.Context, cfg objectstore.Config, driver objectstore.Driver) error {
|
||||
testBackend, err := objectstore.NewBackend(ctx, cfg, driver)
|
||||
if err != nil {
|
||||
return fmt.Errorf("初始化测试存储实例失败: %w", err)
|
||||
return fmt.Errorf("failed to initialize test storage instance: %w", err)
|
||||
}
|
||||
if err := testBackend.Test(ctx); err != nil {
|
||||
return fmt.Errorf("存储连通性测试失败: %w", err)
|
||||
return fmt.Errorf("storage connectivity test failed: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -7,17 +7,17 @@ package task
|
||||
|
||||
// 任务管理相关错误消息
|
||||
const (
|
||||
InvalidTaskType = "无效的任务类型"
|
||||
InvalidTimeRange = "无效的时间范围"
|
||||
TaskDispatchFailed = "任务下发失败"
|
||||
UserIDRequired = "用户ID必填"
|
||||
TaskNotFound = "任务执行记录不存在"
|
||||
TaskNotRetryable = "该任务不支持重试"
|
||||
TaskNotFailed = "只有失败的任务才能重试"
|
||||
TaskMaxRetryExceeded = "已达到最大重试次数"
|
||||
TaskRetryFailed = "任务重试失败"
|
||||
InvalidCronExpression = "无效的 Cron 表达式"
|
||||
ScheduleNotFound = "定时任务不存在"
|
||||
ScheduleSaveFailed = "保存定时任务失败"
|
||||
ScheduleDeleteFailed = "删除定时任务失败"
|
||||
InvalidTaskType = "Invalid task type"
|
||||
InvalidTimeRange = "Invalid time range"
|
||||
TaskDispatchFailed = "Failed to dispatch task"
|
||||
UserIDRequired = "User ID is required"
|
||||
TaskNotFound = "Task execution was not found"
|
||||
TaskNotRetryable = "this task cannot be retried"
|
||||
TaskNotFailed = "Only failed tasks can be retried"
|
||||
TaskMaxRetryExceeded = "Maximum retry count reached"
|
||||
TaskRetryFailed = "Failed to retry task"
|
||||
InvalidCronExpression = "Invalid Cron expression"
|
||||
ScheduleNotFound = "Schedule was not found"
|
||||
ScheduleSaveFailed = "Failed to save schedule"
|
||||
ScheduleDeleteFailed = "Failed to delete schedule"
|
||||
)
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package task
|
||||
|
||||
import (
|
||||
"slices"
|
||||
|
||||
"github.com/Rain-kl/Wavelet/internal/infra/task"
|
||||
"github.com/Rain-kl/Wavelet/internal/model"
|
||||
"github.com/Rain-kl/Wavelet/pkg/i18n"
|
||||
)
|
||||
|
||||
// Localize copies, never the shared registry or persistent task records.
|
||||
func localizeTaskMeta(locale string, meta task.TaskMeta) task.TaskMeta {
|
||||
meta.Name = i18n.Translate(locale, meta.Name)
|
||||
meta.Description = i18n.Translate(locale, meta.Description)
|
||||
meta.Params = slices.Clone(meta.Params)
|
||||
for index := range meta.Params {
|
||||
param := &meta.Params[index]
|
||||
param.Label = i18n.Translate(locale, param.Label)
|
||||
param.Placeholder = i18n.Translate(locale, param.Placeholder)
|
||||
param.Description = i18n.Translate(locale, param.Description)
|
||||
}
|
||||
return meta
|
||||
}
|
||||
|
||||
func localizeTaskExecution(locale string, execution model.TaskExecution) model.TaskExecution {
|
||||
execution.TaskName = i18n.Translate(locale, execution.TaskName)
|
||||
execution.Log = i18n.TranslateLog(locale, execution.Log)
|
||||
execution.ErrorMessage = i18n.Translate(locale, execution.ErrorMessage)
|
||||
execution.Result = i18n.Translate(locale, execution.Result)
|
||||
return execution
|
||||
}
|
||||
|
||||
func localizeTaskExecutions(locale string, executions []model.TaskExecution) []model.TaskExecution {
|
||||
localized := slices.Clone(executions)
|
||||
for index := range localized {
|
||||
localized[index] = localizeTaskExecution(locale, localized[index])
|
||||
}
|
||||
return localized
|
||||
}
|
||||
|
||||
func localizeScheduleName(locale, name string, meta *task.TaskMeta) string {
|
||||
// Only the built-in default name is system text. Custom schedule names are data.
|
||||
if meta != nil && meta.Type == "system_cleanup" && i18n.Translate("en", name) == "Scheduled system cleanup" {
|
||||
return i18n.Translate(locale, "Scheduled system cleanup")
|
||||
}
|
||||
if meta != nil && i18n.Translate("en", name) == meta.Name {
|
||||
return i18n.Translate(locale, meta.Name)
|
||||
}
|
||||
return name
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package task
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/Rain-kl/Wavelet/internal/infra/task"
|
||||
"github.com/Rain-kl/Wavelet/internal/model"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestLocalizeTaskMetaDoesNotMutateSharedParams(t *testing.T) {
|
||||
source := task.TaskMeta{
|
||||
Name: "Switch log database", AsynqTask: "openflare:log_db_switch",
|
||||
Params: []task.TaskParam{{Name: "target", Label: "Target log database", Placeholder: "postgres|sqlite|clickhouse"}},
|
||||
}
|
||||
localized := localizeTaskMeta("zh-CN", source)
|
||||
assert.Equal(t, "切换日志数据库", localized.Name)
|
||||
assert.Equal(t, "目标日志库", localized.Params[0].Label)
|
||||
assert.Equal(t, "openflare:log_db_switch", localized.AsynqTask)
|
||||
assert.Equal(t, "target", localized.Params[0].Name)
|
||||
assert.Equal(t, "Target log database", source.Params[0].Label)
|
||||
}
|
||||
|
||||
func TestLocalizeTaskExecutionsPreservesSourceAndPayload(t *testing.T) {
|
||||
source := []model.TaskExecution{{
|
||||
TaskName: "OpenFlare SSL 自动续期", Log: "[12:34:56] 开始扫描待续期证书\n",
|
||||
Payload: `{"name":"开始扫描待续期证书"}`, TriggeredBy: "用户甲",
|
||||
}}
|
||||
localized := localizeTaskExecutions("en", source)
|
||||
assert.Equal(t, "OpenFlare automatic SSL renewal", localized[0].TaskName)
|
||||
assert.Equal(t, "[12:34:56] Scanning certificates due for renewal\n", localized[0].Log)
|
||||
assert.Equal(t, source[0].Payload, localized[0].Payload)
|
||||
assert.Equal(t, source[0].TriggeredBy, localized[0].TriggeredBy)
|
||||
assert.Equal(t, "OpenFlare SSL 自动续期", source[0].TaskName)
|
||||
}
|
||||
|
||||
func TestLocalizeScheduleNamePreservesCustomNames(t *testing.T) {
|
||||
meta := &task.TaskMeta{Type: "system_cleanup", Name: "System cleanup"}
|
||||
assert.Equal(t, "Scheduled system cleanup", localizeScheduleName("en", "系统定期垃圾清理", meta))
|
||||
assert.Equal(t, "系统定期垃圾清理", localizeScheduleName("zh-CN", "Scheduled system cleanup", meta))
|
||||
assert.Equal(t, "自定义每周清理", localizeScheduleName("en", "自定义每周清理", meta))
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
@@ -35,7 +36,11 @@ import (
|
||||
// @Failure 403 {object} response.Any "无管理员权限"
|
||||
// @Router /api/v1/admin/tasks/types [get]
|
||||
func ListTaskTypes(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, response.OK(task.GetDispatchableTasks()))
|
||||
metas := task.GetDispatchableTasks()
|
||||
for index := range metas {
|
||||
metas[index] = localizeTaskMeta(response.Locale(c), metas[index])
|
||||
}
|
||||
c.JSON(http.StatusOK, response.OK(metas))
|
||||
}
|
||||
|
||||
// DispatchTaskRequest 下发任务请求
|
||||
@@ -130,7 +135,7 @@ func ListTaskExecutions(c *gin.Context) {
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.OK(gin.H{
|
||||
"items": executions,
|
||||
"items": localizeTaskExecutions(response.Locale(c), executions),
|
||||
"total": total,
|
||||
"page": req.Page,
|
||||
"page_size": req.PageSize,
|
||||
@@ -163,7 +168,8 @@ func GetTaskExecution(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.OK(execution))
|
||||
localized := localizeTaskExecution(response.Locale(c), *execution)
|
||||
c.JSON(http.StatusOK, response.OK(localized))
|
||||
}
|
||||
|
||||
// RetryTask 重试失败的任务
|
||||
@@ -190,10 +196,11 @@ func RetryTask(c *gin.Context) {
|
||||
newTaskID, err := task.RetryTask(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
errMsg := err.Error()
|
||||
var retryErr *task.RetryError
|
||||
switch {
|
||||
case strings.Contains(errMsg, "不存在"):
|
||||
case errors.As(err, &retryErr) && retryErr.NotFound:
|
||||
response.AbortNotFound(c, errMsg)
|
||||
case strings.Contains(errMsg, "只有失败的任务") || strings.Contains(errMsg, "不支持重试") || strings.Contains(errMsg, "已达到最大重试"):
|
||||
case retryErr != nil:
|
||||
response.AbortBadRequest(c, errMsg)
|
||||
default:
|
||||
response.AbortInternal(c, fmt.Sprintf("%s: %v", TaskRetryFailed, err))
|
||||
@@ -226,6 +233,7 @@ func ListSchedules(c *gin.Context) {
|
||||
if meta != nil && meta.InternalOnly {
|
||||
continue
|
||||
}
|
||||
schedule.Name = localizeScheduleName(response.Locale(c), schedule.Name, meta)
|
||||
visible = append(visible, schedule)
|
||||
}
|
||||
c.JSON(http.StatusOK, response.OK(visible))
|
||||
@@ -300,7 +308,7 @@ func CreateSchedule(c *gin.Context) {
|
||||
|
||||
// 触发调度服务重载
|
||||
if err := scheduler.ReloadScheduler(); err != nil {
|
||||
logger.ErrorF(c.Request.Context(), "[TaskAdmin] 重载调度器失败: %v", err)
|
||||
logger.ErrorF(c.Request.Context(), "[TaskAdmin] Failed to reload scheduler: %v", err)
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.OK(schedule))
|
||||
@@ -334,7 +342,7 @@ type UpdateScheduleRequest struct {
|
||||
func UpdateSchedule(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
response.AbortBadRequest(c, "无效的定时任务ID")
|
||||
response.AbortBadRequest(c, "Invalid schedule ID")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -392,7 +400,7 @@ func UpdateSchedule(c *gin.Context) {
|
||||
|
||||
// 触发调度服务重载
|
||||
if err := scheduler.ReloadScheduler(); err != nil {
|
||||
logger.ErrorF(c.Request.Context(), "[TaskAdmin] 重载调度器失败: %v", err)
|
||||
logger.ErrorF(c.Request.Context(), "[TaskAdmin] Failed to reload scheduler: %v", err)
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.OK(schedule))
|
||||
@@ -423,7 +431,7 @@ func getAdminTaskMeta(taskType string) *task.TaskMeta {
|
||||
func DeleteSchedule(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
response.AbortBadRequest(c, "无效的定时任务ID")
|
||||
response.AbortBadRequest(c, "Invalid schedule ID")
|
||||
return
|
||||
}
|
||||
schedule, err := repository.GetScheduleByID(c.Request.Context(), id)
|
||||
@@ -443,7 +451,7 @@ func DeleteSchedule(c *gin.Context) {
|
||||
|
||||
// 触发调度服务重载
|
||||
if err := scheduler.ReloadScheduler(); err != nil {
|
||||
logger.ErrorF(c.Request.Context(), "[TaskAdmin] 重载调度器失败: %v", err)
|
||||
logger.ErrorF(c.Request.Context(), "[TaskAdmin] Failed to reload scheduler: %v", err)
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response.OKNil())
|
||||
|
||||
@@ -410,7 +410,7 @@ func TestDispatchTask(t *testing.T) {
|
||||
assert.Equal(t, http.StatusBadRequest, w.Code)
|
||||
var resp response.Any
|
||||
json.Unmarshal(w.Body.Bytes(), &resp)
|
||||
assert.Contains(t, resp.ErrorMsg, "无效的 JSON 格式")
|
||||
assert.Contains(t, resp.ErrorMsg, "invalid JSON format")
|
||||
})
|
||||
|
||||
t.Run("dispatch send_email task failure with missing fields", func(t *testing.T) {
|
||||
@@ -427,7 +427,7 @@ func TestDispatchTask(t *testing.T) {
|
||||
assert.Equal(t, http.StatusBadRequest, w.Code)
|
||||
var resp response.Any
|
||||
json.Unmarshal(w.Body.Bytes(), &resp)
|
||||
assert.Contains(t, resp.ErrorMsg, "不能为空")
|
||||
assert.Contains(t, resp.ErrorMsg, "must not be empty")
|
||||
})
|
||||
|
||||
t.Run("dispatch invalid task type failure", func(t *testing.T) {
|
||||
|
||||
@@ -6,11 +6,11 @@ package template
|
||||
|
||||
// 模板管理相关错误消息
|
||||
const (
|
||||
TemplateNotFound = "模板不存在"
|
||||
TemplateKeyRequired = "模板标识符不能为空"
|
||||
TemplateNameRequired = "模板名称不能为空"
|
||||
TemplateContentRequired = "模板内容不能为空"
|
||||
TemplateKeyExists = "模板标识符已存在"
|
||||
SystemTemplateCannotDelete = "系统预置模板不可删除"
|
||||
SystemTemplateCannotModifyKey = "系统预置模板不可修改标识符"
|
||||
TemplateNotFound = "Template was not found"
|
||||
TemplateKeyRequired = "Template identifier must not be empty"
|
||||
TemplateNameRequired = "Template name must not be empty"
|
||||
TemplateContentRequired = "Template content must not be empty"
|
||||
TemplateKeyExists = "template identifier already exists"
|
||||
SystemTemplateCannotDelete = "built-in templates cannot be deleted"
|
||||
SystemTemplateCannotModifyKey = "Built-in template identifiers cannot be changed"
|
||||
)
|
||||
|
||||
@@ -5,13 +5,13 @@
|
||||
package updater
|
||||
|
||||
const (
|
||||
errInvalidRepository = "上游仓库地址无效"
|
||||
errReleaseRequestFailed = "获取上游版本失败"
|
||||
errReleaseResponseInvalid = "上游版本响应无效"
|
||||
errNoCompatibleRelease = "未找到兼容的 Release"
|
||||
errNoCompatibleAsset = "未找到当前系统对应的 Release 资产"
|
||||
errDevelopmentBuild = "开发版本无法执行自动升级"
|
||||
errAlreadyUpToDate = "当前已是最新版本"
|
||||
errUpgradeAlreadyRunning = "已有升级任务正在执行"
|
||||
errAutomaticUpgradeBlocked = "当前平台暂不支持自动替换二进制"
|
||||
errInvalidRepository = "invalid upstream repository URL"
|
||||
errReleaseRequestFailed = "Failed to fetch upstream version"
|
||||
errReleaseResponseInvalid = "Invalid upstream version response"
|
||||
errNoCompatibleRelease = "no compatible release was found"
|
||||
errNoCompatibleAsset = "no release asset was found for the current platform"
|
||||
errDevelopmentBuild = "development builds do not support automatic updates"
|
||||
errAlreadyUpToDate = "already running the latest version"
|
||||
errUpgradeAlreadyRunning = "an update is already in progress"
|
||||
errAutomaticUpgradeBlocked = "automatic binary replacement is not supported on this platform"
|
||||
)
|
||||
|
||||
@@ -265,42 +265,42 @@ func (m *manager) status(ctx context.Context) (Status, releaseAsset, error) {
|
||||
|
||||
func downloadArchive(ctx context.Context, client releaseClient, asset releaseAsset, destination string) error {
|
||||
if asset.Size <= 0 || asset.Size > maxArchiveSize {
|
||||
return fmt.Errorf("release 资产大小无效: %d", asset.Size)
|
||||
return fmt.Errorf("invalid release asset size: %d", asset.Size)
|
||||
}
|
||||
logger.InfoF(ctx, "[Updater] Downloading release asset: %s", asset.Name)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, asset.BrowserDownloadURL, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("创建升级下载请求失败: %w", err)
|
||||
return fmt.Errorf("failed to create update download request: %w", err)
|
||||
}
|
||||
req.Header.Set("User-Agent", "OpenFlare-Updater")
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("下载升级资产失败: %w", err)
|
||||
return fmt.Errorf("failed to download update asset: %w", err)
|
||||
}
|
||||
defer func() {
|
||||
// The downloaded body has already been validated by size before use.
|
||||
_ = resp.Body.Close()
|
||||
}()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("下载升级资产失败: HTTP %d", resp.StatusCode)
|
||||
return fmt.Errorf("failed to download update asset: HTTP %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
file, err := os.OpenFile(destination, os.O_CREATE|os.O_EXCL|os.O_WRONLY, archiveFileMode) //nolint:gosec // destination is created inside the verified executable directory.
|
||||
if err != nil {
|
||||
return fmt.Errorf("创建升级归档失败: %w", err)
|
||||
return fmt.Errorf("failed to create update archive: %w", err)
|
||||
}
|
||||
|
||||
written, err := io.Copy(file, io.LimitReader(resp.Body, maxArchiveSize+1))
|
||||
if err != nil {
|
||||
_ = file.Close()
|
||||
return fmt.Errorf("写入升级归档失败: %w", err)
|
||||
return fmt.Errorf("failed to write update archive: %w", err)
|
||||
}
|
||||
if err := file.Close(); err != nil {
|
||||
return fmt.Errorf("关闭升级归档失败: %w", err)
|
||||
return fmt.Errorf("failed to close update archive: %w", err)
|
||||
}
|
||||
if written > maxArchiveSize || written != asset.Size {
|
||||
return fmt.Errorf("升级归档大小不匹配: got %d, want %d", written, asset.Size)
|
||||
return fmt.Errorf("update archive size mismatch: got %d, want %d", written, asset.Size)
|
||||
}
|
||||
logger.InfoF(ctx, "[Updater] Successfully downloaded release asset to %s", destination)
|
||||
return nil
|
||||
@@ -309,12 +309,12 @@ func downloadArchive(ctx context.Context, client releaseClient, asset releaseAss
|
||||
func safeArchivePath(destination, name string) (string, error) {
|
||||
cleanName := filepath.Clean(name)
|
||||
if filepath.IsAbs(cleanName) || cleanName == "." || strings.HasPrefix(cleanName, ".."+string(filepath.Separator)) {
|
||||
return "", fmt.Errorf("归档包含非法路径: %s", name)
|
||||
return "", fmt.Errorf("archive contains an invalid path: %s", name)
|
||||
}
|
||||
target := filepath.Join(destination, cleanName)
|
||||
relative, err := filepath.Rel(destination, target)
|
||||
if err != nil || relative == ".." || strings.HasPrefix(relative, ".."+string(filepath.Separator)) {
|
||||
return "", fmt.Errorf("归档路径越界: %s", name)
|
||||
return "", fmt.Errorf("archive path escapes the destination: %s", name)
|
||||
}
|
||||
return target, nil
|
||||
}
|
||||
@@ -510,7 +510,7 @@ func extractTarGz(ctx context.Context, archivePath, destination, targetName stri
|
||||
return "", closeErr
|
||||
}
|
||||
if written > maxArchiveSize {
|
||||
return "", errors.New("解压后的程序文件超过大小限制")
|
||||
return "", errors.New("extracted executable exceeds the size limit")
|
||||
}
|
||||
logger.InfoF(ctx, "[Updater] Successfully extracted binary to %s", target)
|
||||
return target, nil
|
||||
@@ -563,7 +563,7 @@ func extractZip(ctx context.Context, archivePath, destination, targetName string
|
||||
return "", outputCloseErr
|
||||
}
|
||||
if written > maxArchiveSize {
|
||||
return "", errors.New("解压后的程序文件超过大小限制")
|
||||
return "", errors.New("extracted executable exceeds the size limit")
|
||||
}
|
||||
logger.InfoF(ctx, "[Updater] Successfully extracted binary to %s", target)
|
||||
return target, nil
|
||||
@@ -597,16 +597,16 @@ func (m *manager) prepareUpgrade(ctx context.Context) (string, string, error) {
|
||||
|
||||
executable, err := os.Executable()
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("定位当前程序失败: %w", err)
|
||||
return "", "", fmt.Errorf("failed to locate current executable: %w", err)
|
||||
}
|
||||
executable, err = filepath.EvalSymlinks(executable)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("解析当前程序路径失败: %w", err)
|
||||
return "", "", fmt.Errorf("failed to resolve current executable path: %w", err)
|
||||
}
|
||||
|
||||
tempDir, err := os.MkdirTemp(filepath.Dir(executable), ".wavelet-update-*")
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("创建升级目录失败: %w", err)
|
||||
return "", "", fmt.Errorf("failed to create update directory: %w", err)
|
||||
}
|
||||
|
||||
archivePath := filepath.Join(tempDir, asset.Name)
|
||||
@@ -628,7 +628,7 @@ func (m *manager) prepareUpgrade(ctx context.Context) (string, string, error) {
|
||||
if err != nil {
|
||||
// Cleanup is best effort because the extraction error is the actionable failure.
|
||||
_ = os.RemoveAll(tempDir)
|
||||
return "", "", fmt.Errorf("解压升级资产失败: %w", err)
|
||||
return "", "", fmt.Errorf("failed to extract update asset: %w", err)
|
||||
}
|
||||
logger.InfoF(ctx, "[Updater] Staged binary successfully prepared: %s", stagedBinary)
|
||||
m.upgrading = true
|
||||
|
||||
@@ -23,22 +23,22 @@ func replaceAndRestart(executable, stagedBinary string) error {
|
||||
backup := executable + ".old"
|
||||
|
||||
if err := os.Remove(backup); err != nil && !os.IsNotExist(err) {
|
||||
return fmt.Errorf("删除旧备份失败: %w", err)
|
||||
return fmt.Errorf("failed to remove previous backup: %w", err)
|
||||
}
|
||||
|
||||
if err := os.Rename(executable, backup); err != nil {
|
||||
return fmt.Errorf("备份当前程序失败: %w", err)
|
||||
return fmt.Errorf("failed to back up current executable: %w", err)
|
||||
}
|
||||
|
||||
if err := os.Rename(stagedBinary, executable); err != nil {
|
||||
_ = os.Rename(backup, executable)
|
||||
return fmt.Errorf("替换当前程序失败: %w", err)
|
||||
return fmt.Errorf("failed to replace current executable: %w", err)
|
||||
}
|
||||
|
||||
if err := os.Chmod(executable, installedBinaryMode); err != nil { //nolint:gosec // the installed application binary must be executable.
|
||||
_ = os.Remove(executable)
|
||||
_ = os.Rename(backup, executable)
|
||||
return fmt.Errorf("设置程序执行权限失败: %w", err)
|
||||
return fmt.Errorf("failed to set executable permissions: %w", err)
|
||||
}
|
||||
|
||||
stagingDir := filepath.Dir(stagedBinary)
|
||||
|
||||
@@ -6,18 +6,18 @@
|
||||
package user
|
||||
|
||||
const (
|
||||
userNotFound = "用户不存在"
|
||||
cannotDisable = "不能禁用管理员用户"
|
||||
cannotDelete = "不能删除管理员用户"
|
||||
cannotDeleteSelf = "不能删除当前登录用户"
|
||||
updateUserFailed = "更新用户状态失败"
|
||||
deleteUserFailed = "删除用户失败"
|
||||
usernameExists = "用户名已存在"
|
||||
usernameRequired = "用户名不能为空"
|
||||
passwordTooShort = "密码长度不能少于 8 位" //nolint:gosec // false positive: this is an error message, not hardcoded credentials
|
||||
createUserFailed = "创建用户失败"
|
||||
emailRequired = "邮箱不能为空"
|
||||
emailExists = "邮箱已被注册"
|
||||
cannotRevokeSelfAdmin = "不能撤销当前登录用户的管理员权限"
|
||||
updateUserInfoFailed = "更新用户信息失败"
|
||||
userNotFound = "user was not found"
|
||||
cannotDisable = "administrator accounts cannot be disabled"
|
||||
cannotDelete = "administrator accounts cannot be deleted"
|
||||
cannotDeleteSelf = "the currently signed-in user cannot be deleted"
|
||||
updateUserFailed = "Failed to update user status"
|
||||
deleteUserFailed = "Failed to delete user"
|
||||
usernameExists = "username already exists"
|
||||
usernameRequired = "username must not be empty"
|
||||
passwordTooShort = "password must contain at least 8 characters" //nolint:gosec // false positive: this is an error message, not hardcoded credentials
|
||||
createUserFailed = "Failed to create user"
|
||||
emailRequired = "email address must not be empty"
|
||||
emailExists = "email address is already registered"
|
||||
cannotRevokeSelfAdmin = "administrator privileges cannot be revoked from the currently signed-in user"
|
||||
updateUserInfoFailed = "Failed to update user information"
|
||||
)
|
||||
|
||||
@@ -103,7 +103,7 @@ func abortUserLogicError(c *gin.Context, err error, notFoundMsg string, forbidde
|
||||
return true
|
||||
}
|
||||
logger.ErrorF(c.Request.Context(), "Admin user error: %v", err)
|
||||
response.AbortInternal(c, "内部服务器错误")
|
||||
response.AbortInternal(c, "Internal server error")
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -130,7 +130,7 @@ func ListUsers(c *gin.Context) {
|
||||
total, modelUsers, err := listUsers(c.Request.Context(), req)
|
||||
if err != nil {
|
||||
logger.ErrorF(c.Request.Context(), "List admin users failed: %v", err)
|
||||
response.AbortInternal(c, "获取用户列表失败")
|
||||
response.AbortInternal(c, "Failed to get user list")
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user