完善续期通知与前端界面
This commit is contained in:
1 parent
25419c027f
commit
45f895d0c4
64 files changed
+2948
-487
No files matched your search
+63
-16
@@ -150,18 +150,19 @@ func (i *ItemReplies) AllForUser(ctx context.Context, cookieID string) ([]ItemRe
|
||||
|
||||
// NotificationChannelRow 通知渠道完整行(含 id)。
|
||||
type NotificationChannelRow struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Config string `json:"config"`
|
||||
Enabled bool `json:"enabled"`
|
||||
UserID int64 `json:"user_id,omitempty"`
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Config string `json:"config"`
|
||||
EventTypes string `json:"event_types,omitempty"`
|
||||
Enabled bool `json:"enabled"`
|
||||
UserID int64 `json:"user_id,omitempty"`
|
||||
}
|
||||
|
||||
// AllChannelsForUser 取某用户全部通知渠道。
|
||||
func (n *Notifications) AllChannelsForUser(ctx context.Context, userID int64) ([]NotificationChannelRow, error) {
|
||||
rows, err := n.DB.QueryContext(ctx,
|
||||
`SELECT id, name, type, config, enabled, COALESCE(user_id,1) FROM notification_channels
|
||||
`SELECT id, name, type, config, COALESCE(event_types,''), enabled, COALESCE(user_id,1) FROM notification_channels
|
||||
WHERE user_id=? ORDER BY id DESC`, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -171,7 +172,7 @@ func (n *Notifications) AllChannelsForUser(ctx context.Context, userID int64) ([
|
||||
for rows.Next() {
|
||||
var c NotificationChannelRow
|
||||
var enabled int
|
||||
if err := rows.Scan(&c.ID, &c.Name, &c.Type, &c.Config, &enabled, &c.UserID); err != nil {
|
||||
if err := rows.Scan(&c.ID, &c.Name, &c.Type, &c.Config, &c.EventTypes, &enabled, &c.UserID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.Enabled = enabled != 0
|
||||
@@ -183,30 +184,77 @@ func (n *Notifications) AllChannelsForUser(ctx context.Context, userID int64) ([
|
||||
// CreateChannel 创建通知渠道。
|
||||
func (n *Notifications) CreateChannel(ctx context.Context, c *NotificationChannelRow) (int64, error) {
|
||||
return insertReturningID(ctx, n.DB, n.Dialect,
|
||||
`INSERT INTO notification_channels (name, type, config, enabled, user_id) VALUES (?,?,?,?,?)`,
|
||||
c.Name, c.Type, c.Config, boolToInt(c.Enabled), c.UserID)
|
||||
`INSERT INTO notification_channels (name, type, config, event_types, enabled, user_id) VALUES (?,?,?,?,?,?)`,
|
||||
c.Name, c.Type, c.Config, c.EventTypes, boolToInt(c.Enabled), c.UserID)
|
||||
}
|
||||
|
||||
// UpdateChannel 更新通知渠道。
|
||||
func (n *Notifications) UpdateChannel(ctx context.Context, c *NotificationChannelRow) error {
|
||||
_, err := n.DB.ExecContext(ctx,
|
||||
`UPDATE notification_channels SET name=?, type=?, config=?, enabled=?, updated_at=CURRENT_TIMESTAMP WHERE id=?`,
|
||||
c.Name, c.Type, c.Config, boolToInt(c.Enabled), c.ID)
|
||||
`UPDATE notification_channels SET name=?, type=?, config=?, event_types=?, enabled=?, updated_at=CURRENT_TIMESTAMP WHERE id=?`,
|
||||
c.Name, c.Type, c.Config, c.EventTypes, boolToInt(c.Enabled), c.ID)
|
||||
return err
|
||||
}
|
||||
|
||||
// GetChannelRowForUser 按用户取单个通知渠道。未找到返回 nil。
|
||||
func (n *Notifications) GetChannelRowForUser(ctx context.Context, id, userID int64) (*NotificationChannelRow, error) {
|
||||
row := n.DB.QueryRowContext(ctx,
|
||||
`SELECT id, name, type, config, COALESCE(event_types,''), enabled, COALESCE(user_id,1)
|
||||
FROM notification_channels WHERE id=? AND user_id=?`, id, userID)
|
||||
var c NotificationChannelRow
|
||||
var enabled int
|
||||
if err := row.Scan(&c.ID, &c.Name, &c.Type, &c.Config, &c.EventTypes, &enabled, &c.UserID); err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
c.Enabled = enabled != 0
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
// UpdateChannelForUser 更新指定用户拥有的通知渠道。
|
||||
func (n *Notifications) UpdateChannelForUser(ctx context.Context, c *NotificationChannelRow, userID int64) error {
|
||||
res, err := n.DB.ExecContext(ctx,
|
||||
`UPDATE notification_channels
|
||||
SET name=?, type=?, config=?, event_types=?, enabled=?, updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND user_id=?`,
|
||||
c.Name, c.Type, c.Config, c.EventTypes, boolToInt(c.Enabled), c.ID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rows, err := res.RowsAffected()
|
||||
if err == nil && rows == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteChannel 删除通知渠道。
|
||||
func (n *Notifications) DeleteChannel(ctx context.Context, id int64) error {
|
||||
_, err := n.DB.ExecContext(ctx, `DELETE FROM notification_channels WHERE id=?`, id)
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteChannelForUser 删除指定用户拥有的通知渠道。
|
||||
func (n *Notifications) DeleteChannelForUser(ctx context.Context, id, userID int64) error {
|
||||
res, err := n.DB.ExecContext(ctx, `DELETE FROM notification_channels WHERE id=? AND user_id=?`, id, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rows, err := res.RowsAffected()
|
||||
if err == nil && rows == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetChannel 按 ID 取单个通知渠道(含 config)。未找到返回 nil。
|
||||
func (n *Notifications) GetChannel(ctx context.Context, id int64) (*NotificationChannel, error) {
|
||||
row := n.DB.QueryRowContext(ctx,
|
||||
`SELECT id, name, type, config FROM notification_channels WHERE id=?`, id)
|
||||
`SELECT id, name, type, config, COALESCE(event_types,'') FROM notification_channels WHERE id=?`, id)
|
||||
var c NotificationChannel
|
||||
if err := row.Scan(&c.ID, &c.Name, &c.Type, &c.Config); err != nil {
|
||||
if err := row.Scan(&c.ID, &c.Name, &c.Type, &c.Config, &c.EventTypes); err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
@@ -332,8 +380,7 @@ func (s *SystemSettings) Set(ctx context.Context, key, value string) error {
|
||||
|
||||
// PublicSystemKeys 是公开设置键白名单(前端登录页等无需登录可读)。
|
||||
var PublicSystemKeys = map[string]bool{
|
||||
"theme_color": true, "registration_enabled": true,
|
||||
"show_default_login_info": true,
|
||||
"theme_color": true,
|
||||
}
|
||||
|
||||
// Public 取公开设置子集。
|
||||
|
||||
@@ -252,9 +252,10 @@ func TestSettings_Public(t *testing.T) {
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
|
||||
// 写入一个公开 key + 一个私有 key。
|
||||
// 写入一个公开 key + 几个遗留/私有 key。
|
||||
s.Settings.Set(ctx, "theme_color", "blue")
|
||||
s.Settings.Set(ctx, "registration_enabled", "true")
|
||||
s.Settings.Set(ctx, "show_default_login_info", "true")
|
||||
s.Settings.Set(ctx, "private_secret", "topsecret")
|
||||
s.Settings.Set(ctx, "qq_reply_secret_key", "should-not-leak")
|
||||
|
||||
@@ -262,7 +263,7 @@ func TestSettings_Public(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("Public: %v", err)
|
||||
}
|
||||
if pub["theme_color"] != "blue" || pub["registration_enabled"] != "true" {
|
||||
if pub["theme_color"] != "blue" {
|
||||
t.Fatalf("公开 key 缺失: %#v", pub)
|
||||
}
|
||||
// 私有 key 不应出现。
|
||||
@@ -275,9 +276,11 @@ func TestSettings_Public(t *testing.T) {
|
||||
if _, ok := pub["login_captcha_enabled"]; ok {
|
||||
t.Fatal("未实现的登录验证码开关不应公开")
|
||||
}
|
||||
// 白名单内其它默认 key(show_default_login_info)也应可见。
|
||||
if pub["show_default_login_info"] != "true" {
|
||||
t.Fatalf("show_default_login_info 应为 true, got %q", pub["show_default_login_info"])
|
||||
if _, ok := pub["registration_enabled"]; ok {
|
||||
t.Fatal("未实现的注册开关不应公开")
|
||||
}
|
||||
if _, ok := pub["show_default_login_info"]; ok {
|
||||
t.Fatal("未使用的默认登录提示开关不应公开")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"database/sql"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/pressly/goose/v3"
|
||||
)
|
||||
|
||||
// TestMigrate_AppliesCleanSchema 在临时库上跑迁移,验证全量 schema 干净落地、
|
||||
@@ -35,6 +37,18 @@ func TestMigrate_AppliesCleanSchema(t *testing.T) {
|
||||
{"users", "is_admin"},
|
||||
{"sessions", "session_id"},
|
||||
{"notification_channels", "user_id"},
|
||||
{"notification_channels", "event_types"},
|
||||
{"message_notifications", "event_types"},
|
||||
{"scheduled_cookies_refresh_log", "step_details"},
|
||||
{"scheduled_cookies_refresh_log", "renew_method"},
|
||||
{"scheduled_cookies_refresh_log", "duration_ms"},
|
||||
{"scheduled_cookies_refresh_log", "request_count"},
|
||||
{"scheduled_login_renew_log", "step_details"},
|
||||
{"scheduled_login_renew_log", "updated_cookie_count"},
|
||||
{"scheduled_api_cookie_renew_log", "step_details"},
|
||||
{"scheduled_api_cookie_renew_log", "request_count"},
|
||||
{"risk_control_logs", "processing_status"},
|
||||
{"risk_control_logs", "duration_ms"},
|
||||
}
|
||||
for _, c := range checks {
|
||||
if !columnExists(t, db, c.table, c.col) {
|
||||
@@ -52,6 +66,14 @@ func TestMigrate_AppliesCleanSchema(t *testing.T) {
|
||||
if err != nil || val != "" {
|
||||
t.Errorf("qq_reply_secret_key 应为空(无默认值安全基线): val=%q err=%v", val, err)
|
||||
}
|
||||
err = db.QueryRow(`SELECT value FROM system_settings WHERE key='log_level'`).Scan(&val)
|
||||
if err != nil || val != "info" {
|
||||
t.Errorf("log_level 默认设置异常: val=%q err=%v", val, err)
|
||||
}
|
||||
err = db.QueryRow(`SELECT value FROM system_settings WHERE key='renewal_log_retention_days'`).Scan(&val)
|
||||
if err != nil || val != "10" {
|
||||
t.Errorf("renewal_log_retention_days 默认设置异常: val=%q err=%v", val, err)
|
||||
}
|
||||
|
||||
// 二次 Open 应幂等(迁移不重复执行、不报错)。
|
||||
if err := db.Close(); err != nil {
|
||||
@@ -82,3 +104,61 @@ func columnExists(t *testing.T, db *sql.DB, table, col string) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func TestMigration14DownUpSQLite(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
dbPath := filepath.Join(tmp, "rollback.db")
|
||||
ctx := context.Background()
|
||||
d, _, err := Open(ctx, dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Open: %v", err)
|
||||
}
|
||||
defer d.Close()
|
||||
|
||||
if err := goose.SetDialect("sqlite3"); err != nil {
|
||||
t.Fatalf("goose dialect: %v", err)
|
||||
}
|
||||
goose.SetBaseFS(migrationsFS)
|
||||
if err := goose.Down(d, "migrations/sqlite"); err != nil {
|
||||
t.Fatalf("down latest migration: %v", err)
|
||||
}
|
||||
if columnExists(t, d, "notification_channels", "event_types") {
|
||||
t.Fatal("event_types should be removed after migration 14 down")
|
||||
}
|
||||
if tableExists(t, d, "risk_control_logs") {
|
||||
t.Fatal("risk_control_logs should be removed after migration 14 down")
|
||||
}
|
||||
|
||||
if err := goose.Up(d, "migrations/sqlite"); err != nil {
|
||||
t.Fatalf("up after down: %v", err)
|
||||
}
|
||||
for _, c := range []struct {
|
||||
table string
|
||||
col string
|
||||
}{
|
||||
{"notification_channels", "event_types"},
|
||||
{"message_notifications", "event_types"},
|
||||
{"scheduled_cookies_refresh_log", "step_details"},
|
||||
{"scheduled_login_renew_log", "updated_cookie_count"},
|
||||
{"scheduled_api_cookie_renew_log", "request_count"},
|
||||
{"risk_control_logs", "processing_status"},
|
||||
} {
|
||||
if !columnExists(t, d, c.table, c.col) {
|
||||
t.Fatalf("column missing after re-up: %s.%s", c.table, c.col)
|
||||
}
|
||||
}
|
||||
var val string
|
||||
if err := d.QueryRow(`SELECT value FROM system_settings WHERE key='renewal_log_retention_days'`).Scan(&val); err != nil || val != "10" {
|
||||
t.Fatalf("renewal_log_retention_days after re-up: val=%q err=%v", val, err)
|
||||
}
|
||||
}
|
||||
|
||||
func tableExists(t *testing.T, db *sql.DB, table string) bool {
|
||||
t.Helper()
|
||||
var name string
|
||||
err := db.QueryRow(`SELECT name FROM sqlite_master WHERE type='table' AND name=?`, table).Scan(&name)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return name == table
|
||||
}
|
||||
@@ -4,41 +4,41 @@ ALTER TABLE cookies ADD COLUMN last_refresh_at BIGINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE cookie_status ADD COLUMN disable_reason TEXT;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS cookie_refresh_schedules (
|
||||
cookie_id VARCHAR(191) PRIMARY KEY,
|
||||
cookie_id VARCHAR(255) PRIMARY KEY,
|
||||
expire_at BIGINT NOT NULL DEFAULT 0,
|
||||
disabled TINYINT(1) NOT NULL DEFAULT 0,
|
||||
consecutive_failures INT NOT NULL DEFAULT 0,
|
||||
last_error TEXT NOT NULL,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
CONSTRAINT fk_cookie_refresh_schedules_cookie FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
|
||||
);
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS scheduled_cookies_refresh_log (
|
||||
id BIGINT PRIMARY KEY AUTO_INCREMENT,
|
||||
cookie_id VARCHAR(191) NOT NULL,
|
||||
cookie_id VARCHAR(255) NOT NULL,
|
||||
status VARCHAR(32) NOT NULL,
|
||||
message TEXT NOT NULL,
|
||||
updated_cookie_names TEXT NOT NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS scheduled_login_renew_log (
|
||||
id BIGINT PRIMARY KEY AUTO_INCREMENT,
|
||||
cookie_id VARCHAR(191) NOT NULL,
|
||||
cookie_id VARCHAR(255) NOT NULL,
|
||||
status VARCHAR(32) NOT NULL,
|
||||
message TEXT NOT NULL,
|
||||
updated_cookie_names TEXT NOT NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS scheduled_api_cookie_renew_log (
|
||||
id BIGINT PRIMARY KEY AUTO_INCREMENT,
|
||||
cookie_id VARCHAR(191) NOT NULL,
|
||||
cookie_id VARCHAR(255) NOT NULL,
|
||||
status VARCHAR(32) NOT NULL,
|
||||
message TEXT NOT NULL,
|
||||
updated_cookie_names TEXT NOT NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE IF EXISTS scheduled_api_cookie_renew_log;
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
-- +goose Up
|
||||
DROP PROCEDURE IF EXISTS add_xianyu_column_if_missing;
|
||||
-- +goose StatementBegin
|
||||
CREATE PROCEDURE add_xianyu_column_if_missing(
|
||||
IN p_table_name VARCHAR(64),
|
||||
IN p_column_name VARCHAR(64),
|
||||
IN p_column_definition TEXT
|
||||
)
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = p_table_name
|
||||
AND COLUMN_NAME = p_column_name
|
||||
) THEN
|
||||
SET @ddl = CONCAT('ALTER TABLE `', p_table_name, '` ADD COLUMN ', p_column_definition);
|
||||
PREPARE stmt FROM @ddl;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
END IF;
|
||||
END;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CALL add_xianyu_column_if_missing('notification_channels', 'event_types', CONCAT('`event_types` VARCHAR(512) NOT NULL DEFAULT ', QUOTE('')));
|
||||
CALL add_xianyu_column_if_missing('message_notifications', 'event_types', CONCAT('`event_types` VARCHAR(512) NOT NULL DEFAULT ', QUOTE('')));
|
||||
|
||||
CALL add_xianyu_column_if_missing('scheduled_cookies_refresh_log', 'step_details', '`step_details` TEXT');
|
||||
CALL add_xianyu_column_if_missing('scheduled_cookies_refresh_log', 'renew_method', CONCAT('`renew_method` VARCHAR(64) NOT NULL DEFAULT ', QUOTE('')));
|
||||
CALL add_xianyu_column_if_missing('scheduled_cookies_refresh_log', 'duration_ms', '`duration_ms` BIGINT NOT NULL DEFAULT 0');
|
||||
CALL add_xianyu_column_if_missing('scheduled_cookies_refresh_log', 'request_count', '`request_count` INT NOT NULL DEFAULT 0');
|
||||
CALL add_xianyu_column_if_missing('scheduled_cookies_refresh_log', 'response_content', '`response_content` MEDIUMTEXT');
|
||||
|
||||
CALL add_xianyu_column_if_missing('scheduled_login_renew_log', 'step_details', '`step_details` TEXT');
|
||||
CALL add_xianyu_column_if_missing('scheduled_login_renew_log', 'renew_method', CONCAT('`renew_method` VARCHAR(64) NOT NULL DEFAULT ', QUOTE('')));
|
||||
CALL add_xianyu_column_if_missing('scheduled_login_renew_log', 'duration_ms', '`duration_ms` BIGINT NOT NULL DEFAULT 0');
|
||||
CALL add_xianyu_column_if_missing('scheduled_login_renew_log', 'request_count', '`request_count` INT NOT NULL DEFAULT 0');
|
||||
CALL add_xianyu_column_if_missing('scheduled_login_renew_log', 'response_content', '`response_content` MEDIUMTEXT');
|
||||
CALL add_xianyu_column_if_missing('scheduled_login_renew_log', 'updated_cookie_count', '`updated_cookie_count` INT NOT NULL DEFAULT 0');
|
||||
|
||||
CALL add_xianyu_column_if_missing('scheduled_api_cookie_renew_log', 'step_details', '`step_details` TEXT');
|
||||
CALL add_xianyu_column_if_missing('scheduled_api_cookie_renew_log', 'renew_method', CONCAT('`renew_method` VARCHAR(64) NOT NULL DEFAULT ', QUOTE('')));
|
||||
CALL add_xianyu_column_if_missing('scheduled_api_cookie_renew_log', 'duration_ms', '`duration_ms` BIGINT NOT NULL DEFAULT 0');
|
||||
CALL add_xianyu_column_if_missing('scheduled_api_cookie_renew_log', 'request_count', '`request_count` INT NOT NULL DEFAULT 0');
|
||||
|
||||
DROP PROCEDURE IF EXISTS add_xianyu_column_if_missing;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS risk_control_logs (
|
||||
id BIGINT PRIMARY KEY AUTO_INCREMENT,
|
||||
cookie_id VARCHAR(255) NOT NULL,
|
||||
event_type VARCHAR(64) NOT NULL DEFAULT 'slider_captcha',
|
||||
event_description TEXT,
|
||||
processing_result TEXT,
|
||||
processing_status VARCHAR(32) NOT NULL DEFAULT 'processing',
|
||||
captcha_engine VARCHAR(32) NOT NULL DEFAULT '',
|
||||
error_message TEXT,
|
||||
duration_ms BIGINT NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
CONSTRAINT fk_risk_control_logs_cookie FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
INSERT IGNORE INTO system_settings (`key`, value, description) VALUES
|
||||
('log_level', 'info', '日志输出等级:debug/info/warn/error'),
|
||||
('log_format', 'text', '日志输出格式:text/json'),
|
||||
('renewal_log_retention_days', '10', '续期日志保留天数');
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE IF EXISTS risk_control_logs;
|
||||
DELETE FROM system_settings WHERE `key` IN ('log_level', 'log_format', 'renewal_log_retention_days');
|
||||
|
||||
DROP PROCEDURE IF EXISTS drop_xianyu_column_if_exists;
|
||||
-- +goose StatementBegin
|
||||
CREATE PROCEDURE drop_xianyu_column_if_exists(
|
||||
IN p_table_name VARCHAR(64),
|
||||
IN p_column_name VARCHAR(64)
|
||||
)
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1
|
||||
FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = p_table_name
|
||||
AND COLUMN_NAME = p_column_name
|
||||
) THEN
|
||||
SET @ddl = CONCAT('ALTER TABLE `', p_table_name, '` DROP COLUMN `', p_column_name, '`');
|
||||
PREPARE stmt FROM @ddl;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
END IF;
|
||||
END;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CALL drop_xianyu_column_if_exists('notification_channels', 'event_types');
|
||||
CALL drop_xianyu_column_if_exists('message_notifications', 'event_types');
|
||||
CALL drop_xianyu_column_if_exists('scheduled_cookies_refresh_log', 'step_details');
|
||||
CALL drop_xianyu_column_if_exists('scheduled_cookies_refresh_log', 'renew_method');
|
||||
CALL drop_xianyu_column_if_exists('scheduled_cookies_refresh_log', 'duration_ms');
|
||||
CALL drop_xianyu_column_if_exists('scheduled_cookies_refresh_log', 'request_count');
|
||||
CALL drop_xianyu_column_if_exists('scheduled_cookies_refresh_log', 'response_content');
|
||||
CALL drop_xianyu_column_if_exists('scheduled_login_renew_log', 'step_details');
|
||||
CALL drop_xianyu_column_if_exists('scheduled_login_renew_log', 'renew_method');
|
||||
CALL drop_xianyu_column_if_exists('scheduled_login_renew_log', 'duration_ms');
|
||||
CALL drop_xianyu_column_if_exists('scheduled_login_renew_log', 'request_count');
|
||||
CALL drop_xianyu_column_if_exists('scheduled_login_renew_log', 'response_content');
|
||||
CALL drop_xianyu_column_if_exists('scheduled_login_renew_log', 'updated_cookie_count');
|
||||
CALL drop_xianyu_column_if_exists('scheduled_api_cookie_renew_log', 'step_details');
|
||||
CALL drop_xianyu_column_if_exists('scheduled_api_cookie_renew_log', 'renew_method');
|
||||
CALL drop_xianyu_column_if_exists('scheduled_api_cookie_renew_log', 'duration_ms');
|
||||
CALL drop_xianyu_column_if_exists('scheduled_api_cookie_renew_log', 'request_count');
|
||||
|
||||
DROP PROCEDURE IF EXISTS drop_xianyu_column_if_exists;
|
||||
@@ -0,0 +1,63 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE notification_channels ADD COLUMN IF NOT EXISTS event_types TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE message_notifications ADD COLUMN IF NOT EXISTS event_types TEXT NOT NULL DEFAULT '';
|
||||
|
||||
ALTER TABLE scheduled_cookies_refresh_log ADD COLUMN IF NOT EXISTS step_details TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE scheduled_cookies_refresh_log ADD COLUMN IF NOT EXISTS renew_method TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE scheduled_cookies_refresh_log ADD COLUMN IF NOT EXISTS duration_ms BIGINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE scheduled_cookies_refresh_log ADD COLUMN IF NOT EXISTS request_count INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE scheduled_cookies_refresh_log ADD COLUMN IF NOT EXISTS response_content TEXT NOT NULL DEFAULT '';
|
||||
|
||||
ALTER TABLE scheduled_login_renew_log ADD COLUMN IF NOT EXISTS step_details TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE scheduled_login_renew_log ADD COLUMN IF NOT EXISTS renew_method TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE scheduled_login_renew_log ADD COLUMN IF NOT EXISTS duration_ms BIGINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE scheduled_login_renew_log ADD COLUMN IF NOT EXISTS request_count INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE scheduled_login_renew_log ADD COLUMN IF NOT EXISTS response_content TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE scheduled_login_renew_log ADD COLUMN IF NOT EXISTS updated_cookie_count INTEGER NOT NULL DEFAULT 0;
|
||||
|
||||
ALTER TABLE scheduled_api_cookie_renew_log ADD COLUMN IF NOT EXISTS step_details TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE scheduled_api_cookie_renew_log ADD COLUMN IF NOT EXISTS renew_method TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE scheduled_api_cookie_renew_log ADD COLUMN IF NOT EXISTS duration_ms BIGINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE scheduled_api_cookie_renew_log ADD COLUMN IF NOT EXISTS request_count INTEGER NOT NULL DEFAULT 0;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS risk_control_logs (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
cookie_id TEXT NOT NULL REFERENCES cookies(id) ON DELETE CASCADE,
|
||||
event_type TEXT NOT NULL DEFAULT 'slider_captcha',
|
||||
event_description TEXT NOT NULL DEFAULT '',
|
||||
processing_result TEXT NOT NULL DEFAULT '',
|
||||
processing_status TEXT NOT NULL DEFAULT 'processing',
|
||||
captcha_engine TEXT NOT NULL DEFAULT '',
|
||||
error_message TEXT NOT NULL DEFAULT '',
|
||||
duration_ms BIGINT NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
INSERT INTO system_settings (key, value, description) VALUES
|
||||
('log_level', 'info', '日志输出等级:debug/info/warn/error'),
|
||||
('log_format', 'text', '日志输出格式:text/json'),
|
||||
('renewal_log_retention_days', '10', '续期日志保留天数')
|
||||
ON CONFLICT (key) DO NOTHING;
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE IF EXISTS risk_control_logs;
|
||||
DELETE FROM system_settings WHERE key IN ('log_level', 'log_format', 'renewal_log_retention_days');
|
||||
|
||||
ALTER TABLE notification_channels DROP COLUMN IF EXISTS event_types;
|
||||
ALTER TABLE message_notifications DROP COLUMN IF EXISTS event_types;
|
||||
ALTER TABLE scheduled_cookies_refresh_log DROP COLUMN IF EXISTS step_details;
|
||||
ALTER TABLE scheduled_cookies_refresh_log DROP COLUMN IF EXISTS renew_method;
|
||||
ALTER TABLE scheduled_cookies_refresh_log DROP COLUMN IF EXISTS duration_ms;
|
||||
ALTER TABLE scheduled_cookies_refresh_log DROP COLUMN IF EXISTS request_count;
|
||||
ALTER TABLE scheduled_cookies_refresh_log DROP COLUMN IF EXISTS response_content;
|
||||
ALTER TABLE scheduled_login_renew_log DROP COLUMN IF EXISTS step_details;
|
||||
ALTER TABLE scheduled_login_renew_log DROP COLUMN IF EXISTS renew_method;
|
||||
ALTER TABLE scheduled_login_renew_log DROP COLUMN IF EXISTS duration_ms;
|
||||
ALTER TABLE scheduled_login_renew_log DROP COLUMN IF EXISTS request_count;
|
||||
ALTER TABLE scheduled_login_renew_log DROP COLUMN IF EXISTS response_content;
|
||||
ALTER TABLE scheduled_login_renew_log DROP COLUMN IF EXISTS updated_cookie_count;
|
||||
ALTER TABLE scheduled_api_cookie_renew_log DROP COLUMN IF EXISTS step_details;
|
||||
ALTER TABLE scheduled_api_cookie_renew_log DROP COLUMN IF EXISTS renew_method;
|
||||
ALTER TABLE scheduled_api_cookie_renew_log DROP COLUMN IF EXISTS duration_ms;
|
||||
ALTER TABLE scheduled_api_cookie_renew_log DROP COLUMN IF EXISTS request_count;
|
||||
@@ -0,0 +1,63 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE notification_channels ADD COLUMN event_types TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE message_notifications ADD COLUMN event_types TEXT NOT NULL DEFAULT '';
|
||||
|
||||
ALTER TABLE scheduled_cookies_refresh_log ADD COLUMN step_details TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE scheduled_cookies_refresh_log ADD COLUMN renew_method TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE scheduled_cookies_refresh_log ADD COLUMN duration_ms INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE scheduled_cookies_refresh_log ADD COLUMN request_count INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE scheduled_cookies_refresh_log ADD COLUMN response_content TEXT NOT NULL DEFAULT '';
|
||||
|
||||
ALTER TABLE scheduled_login_renew_log ADD COLUMN step_details TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE scheduled_login_renew_log ADD COLUMN renew_method TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE scheduled_login_renew_log ADD COLUMN duration_ms INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE scheduled_login_renew_log ADD COLUMN request_count INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE scheduled_login_renew_log ADD COLUMN response_content TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE scheduled_login_renew_log ADD COLUMN updated_cookie_count INTEGER NOT NULL DEFAULT 0;
|
||||
|
||||
ALTER TABLE scheduled_api_cookie_renew_log ADD COLUMN step_details TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE scheduled_api_cookie_renew_log ADD COLUMN renew_method TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE scheduled_api_cookie_renew_log ADD COLUMN duration_ms INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE scheduled_api_cookie_renew_log ADD COLUMN request_count INTEGER NOT NULL DEFAULT 0;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS risk_control_logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
cookie_id TEXT NOT NULL,
|
||||
event_type TEXT NOT NULL DEFAULT 'slider_captcha',
|
||||
event_description TEXT NOT NULL DEFAULT '',
|
||||
processing_result TEXT NOT NULL DEFAULT '',
|
||||
processing_status TEXT NOT NULL DEFAULT 'processing',
|
||||
captcha_engine TEXT NOT NULL DEFAULT '',
|
||||
error_message TEXT NOT NULL DEFAULT '',
|
||||
duration_ms INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
INSERT OR IGNORE INTO system_settings (key, value, description) VALUES
|
||||
('log_level', 'info', '日志输出等级:debug/info/warn/error'),
|
||||
('log_format', 'text', '日志输出格式:text/json'),
|
||||
('renewal_log_retention_days', '10', '续期日志保留天数');
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE IF EXISTS risk_control_logs;
|
||||
DELETE FROM system_settings WHERE key IN ('log_level', 'log_format', 'renewal_log_retention_days');
|
||||
|
||||
ALTER TABLE notification_channels DROP COLUMN event_types;
|
||||
ALTER TABLE message_notifications DROP COLUMN event_types;
|
||||
ALTER TABLE scheduled_cookies_refresh_log DROP COLUMN step_details;
|
||||
ALTER TABLE scheduled_cookies_refresh_log DROP COLUMN renew_method;
|
||||
ALTER TABLE scheduled_cookies_refresh_log DROP COLUMN duration_ms;
|
||||
ALTER TABLE scheduled_cookies_refresh_log DROP COLUMN request_count;
|
||||
ALTER TABLE scheduled_cookies_refresh_log DROP COLUMN response_content;
|
||||
ALTER TABLE scheduled_login_renew_log DROP COLUMN step_details;
|
||||
ALTER TABLE scheduled_login_renew_log DROP COLUMN renew_method;
|
||||
ALTER TABLE scheduled_login_renew_log DROP COLUMN duration_ms;
|
||||
ALTER TABLE scheduled_login_renew_log DROP COLUMN request_count;
|
||||
ALTER TABLE scheduled_login_renew_log DROP COLUMN response_content;
|
||||
ALTER TABLE scheduled_login_renew_log DROP COLUMN updated_cookie_count;
|
||||
ALTER TABLE scheduled_api_cookie_renew_log DROP COLUMN step_details;
|
||||
ALTER TABLE scheduled_api_cookie_renew_log DROP COLUMN renew_method;
|
||||
ALTER TABLE scheduled_api_cookie_renew_log DROP COLUMN duration_ms;
|
||||
ALTER TABLE scheduled_api_cookie_renew_log DROP COLUMN request_count;
|
||||
@@ -61,3 +61,16 @@ type AccountLoginLog struct {
|
||||
DurationMS int64
|
||||
CreatedAt int64
|
||||
}
|
||||
|
||||
// RiskControlLog 记录滑块/人脸/风控恢复过程。
|
||||
type RiskControlLog struct {
|
||||
ID int64
|
||||
CookieID string
|
||||
EventType string
|
||||
EventDescription string
|
||||
ProcessingResult string
|
||||
ProcessingStatus string
|
||||
CaptchaEngine string
|
||||
ErrorMessage string
|
||||
DurationMS int64
|
||||
}
|
||||
@@ -444,6 +444,47 @@ func TestMultiDB_Notifications(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMultiDB_Migration14DownUp(t *testing.T) {
|
||||
for _, tg := range allTestTargets(t) {
|
||||
t.Run(tg.name, func(t *testing.T) {
|
||||
defer tg.cleanup()
|
||||
subdir, gooseDialect := migrationTestSubdir(t, tg.dialect)
|
||||
if err := goose.SetDialect(gooseDialect); err != nil {
|
||||
t.Fatalf("set goose dialect: %v", err)
|
||||
}
|
||||
goose.SetBaseFS(migrationsFS)
|
||||
if err := goose.Down(tg.store.DB, "migrations/"+subdir); err != nil {
|
||||
t.Fatalf("migration 14 down: %v", err)
|
||||
}
|
||||
if columnExistsForDialect(t, tg.store.DB, tg.dialect, "notification_channels", "event_types") {
|
||||
t.Fatal("notification_channels.event_types should be removed after down")
|
||||
}
|
||||
if tableExistsForDialect(t, tg.store.DB, tg.dialect, "risk_control_logs") {
|
||||
t.Fatal("risk_control_logs should be removed after down")
|
||||
}
|
||||
|
||||
if err := goose.Up(tg.store.DB, "migrations/"+subdir); err != nil {
|
||||
t.Fatalf("migration up after down: %v", err)
|
||||
}
|
||||
for _, c := range []struct {
|
||||
table string
|
||||
col string
|
||||
}{
|
||||
{"notification_channels", "event_types"},
|
||||
{"message_notifications", "event_types"},
|
||||
{"scheduled_cookies_refresh_log", "step_details"},
|
||||
{"scheduled_login_renew_log", "updated_cookie_count"},
|
||||
{"scheduled_api_cookie_renew_log", "request_count"},
|
||||
{"risk_control_logs", "processing_status"},
|
||||
} {
|
||||
if !columnExistsForDialect(t, tg.store.DB, tg.dialect, c.table, c.col) {
|
||||
t.Fatalf("column missing after re-up: %s.%s", c.table, c.col)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestMultiDB_CardsCreateGet 验证 cards Create + Get 的 NULL 列扫描(含 nullable 字段)。
|
||||
func TestMultiDB_CardsCreateGet(t *testing.T) {
|
||||
for _, tg := range allTestTargets(t) {
|
||||
@@ -482,4 +523,83 @@ func TestMultiDB_CardsCreateGet(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func migrationTestSubdir(t *testing.T, dialect Dialect) (string, string) {
|
||||
t.Helper()
|
||||
switch dialect {
|
||||
case DialectSQLite:
|
||||
return "sqlite", "sqlite3"
|
||||
case DialectMySQL:
|
||||
return "mysql", "mysql"
|
||||
case DialectPostgres:
|
||||
return "postgres", "postgres"
|
||||
default:
|
||||
t.Fatalf("unknown dialect: %s", dialect)
|
||||
return "", ""
|
||||
}
|
||||
}
|
||||
|
||||
func columnExistsForDialect(t *testing.T, db *sql.DB, dialect Dialect, table, col string) bool {
|
||||
t.Helper()
|
||||
var query string
|
||||
var args []any
|
||||
switch dialect {
|
||||
case DialectSQLite:
|
||||
rows, err := db.Query(`SELECT name FROM pragma_table_info(?)`, table)
|
||||
if err != nil {
|
||||
t.Fatalf("pragma_table_info(%s): %v", table, err)
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var name string
|
||||
if err := rows.Scan(&name); err != nil {
|
||||
t.Fatalf("scan column name: %v", err)
|
||||
}
|
||||
if name == col {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
t.Fatalf("column rows: %v", err)
|
||||
}
|
||||
return false
|
||||
case DialectMySQL:
|
||||
query = `SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? AND COLUMN_NAME=?`
|
||||
args = []any{table, col}
|
||||
case DialectPostgres:
|
||||
query = `SELECT COUNT(*) FROM information_schema.columns WHERE table_schema='public' AND table_name=? AND column_name=?`
|
||||
args = []any{table, col}
|
||||
default:
|
||||
t.Fatalf("unknown dialect: %s", dialect)
|
||||
}
|
||||
var count int
|
||||
if err := db.QueryRow(query, args...).Scan(&count); err != nil {
|
||||
t.Fatalf("column exists query %s.%s: %v", table, col, err)
|
||||
}
|
||||
return count > 0
|
||||
}
|
||||
|
||||
func tableExistsForDialect(t *testing.T, db *sql.DB, dialect Dialect, table string) bool {
|
||||
t.Helper()
|
||||
var query string
|
||||
var args []any
|
||||
switch dialect {
|
||||
case DialectSQLite:
|
||||
query = `SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name=?`
|
||||
args = []any{table}
|
||||
case DialectMySQL:
|
||||
query = `SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=?`
|
||||
args = []any{table}
|
||||
case DialectPostgres:
|
||||
query = `SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='public' AND table_name=?`
|
||||
args = []any{table}
|
||||
default:
|
||||
t.Fatalf("unknown dialect: %s", dialect)
|
||||
}
|
||||
var count int
|
||||
if err := db.QueryRow(query, args...).Scan(&count); err != nil {
|
||||
t.Fatalf("table exists query %s: %v", table, err)
|
||||
}
|
||||
return count > 0
|
||||
}
|
||||
|
||||
func boolPtr(b bool) *bool { return &b }
|
||||
@@ -7,10 +7,11 @@ import (
|
||||
|
||||
// NotificationChannel 通知渠道(含配置 JSON)。
|
||||
type NotificationChannel struct {
|
||||
ID int64
|
||||
Name string
|
||||
Type string
|
||||
Config string // JSON
|
||||
ID int64
|
||||
Name string
|
||||
Type string
|
||||
Config string // JSON
|
||||
EventTypes string // JSON array or comma-separated event codes
|
||||
}
|
||||
|
||||
// Notifications 通知绑定操作。
|
||||
@@ -23,7 +24,8 @@ type Notifications struct {
|
||||
// 移植自 get_account_notifications。
|
||||
func (n *Notifications) AccountChannels(ctx context.Context, cookieID string) ([]NotificationChannel, error) {
|
||||
rows, err := n.DB.QueryContext(ctx,
|
||||
`SELECT nc.id, nc.name, nc.type, nc.config
|
||||
`SELECT nc.id, nc.name, nc.type, nc.config,
|
||||
COALESCE(NULLIF(mn.event_types,''), nc.event_types, '')
|
||||
FROM message_notifications mn
|
||||
JOIN cookies c ON c.id=mn.cookie_id
|
||||
JOIN notification_channels nc ON mn.channel_id = nc.id AND nc.user_id=c.user_id
|
||||
@@ -36,7 +38,7 @@ func (n *Notifications) AccountChannels(ctx context.Context, cookieID string) ([
|
||||
var out []NotificationChannel
|
||||
for rows.Next() {
|
||||
var c NotificationChannel
|
||||
if err := rows.Scan(&c.ID, &c.Name, &c.Type, &c.Config); err != nil {
|
||||
if err := rows.Scan(&c.ID, &c.Name, &c.Type, &c.Config, &c.EventTypes); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, c)
|
||||
|
||||
+41
-9
@@ -43,6 +43,10 @@ type RenewalLog struct {
|
||||
UpdatedCookieNames []string
|
||||
UpdatedCookieCount int
|
||||
ResponseContent string
|
||||
StepDetails string
|
||||
RenewMethod string
|
||||
DurationMS int64
|
||||
RequestCount int
|
||||
NextExpireAt int64
|
||||
}
|
||||
|
||||
@@ -170,21 +174,29 @@ func (r *RenewalStore) AddBrowserCookieRenewLog(ctx context.Context, log Renewal
|
||||
_, err := r.DB.ExecContext(ctx,
|
||||
`INSERT INTO scheduled_cookies_refresh_log
|
||||
(batch_id, cookie_id, status, message, error_message, updated_cookie_names,
|
||||
updated_cookie_count, next_expire_at, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
|
||||
updated_cookie_count, next_expire_at, step_details, renew_method, duration_ms,
|
||||
request_count, response_content, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
|
||||
log.BatchID, log.CookieID, log.Status, log.Message, firstNonEmpty(log.ErrorMessage, log.Message),
|
||||
strings.Join(log.UpdatedCookieNames, ","), log.UpdatedCookieCount, log.NextExpireAt)
|
||||
strings.Join(log.UpdatedCookieNames, ","), log.UpdatedCookieCount, log.NextExpireAt,
|
||||
log.StepDetails, log.RenewMethod, log.DurationMS, log.RequestCount, log.ResponseContent)
|
||||
return err
|
||||
}
|
||||
|
||||
// AddLoginRenewLog 记录 login_renew 任务日志。
|
||||
func (r *RenewalStore) AddLoginRenewLog(ctx context.Context, log RenewalLog) error {
|
||||
if log.UpdatedCookieCount == 0 {
|
||||
log.UpdatedCookieCount = len(log.UpdatedCookieNames)
|
||||
}
|
||||
_, err := r.DB.ExecContext(ctx,
|
||||
`INSERT INTO scheduled_login_renew_log
|
||||
(batch_id, cookie_id, status, message, error_message, updated_cookie_names, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
|
||||
(batch_id, cookie_id, status, message, error_message, updated_cookie_names,
|
||||
updated_cookie_count, step_details, renew_method, duration_ms, request_count,
|
||||
response_content, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
|
||||
log.BatchID, log.CookieID, log.Status, log.Message, firstNonEmpty(log.ErrorMessage, log.Message),
|
||||
strings.Join(log.UpdatedCookieNames, ","))
|
||||
strings.Join(log.UpdatedCookieNames, ","), log.UpdatedCookieCount, log.StepDetails,
|
||||
log.RenewMethod, log.DurationMS, log.RequestCount, log.ResponseContent)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -196,13 +208,33 @@ func (r *RenewalStore) AddAPICookieRenewLog(ctx context.Context, log RenewalLog)
|
||||
_, err := r.DB.ExecContext(ctx,
|
||||
`INSERT INTO scheduled_api_cookie_renew_log
|
||||
(batch_id, cookie_id, status, message, error_message, updated_cookie_names,
|
||||
updated_cookie_count, response_content, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
|
||||
updated_cookie_count, response_content, step_details, renew_method, duration_ms,
|
||||
request_count, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
|
||||
log.BatchID, log.CookieID, log.Status, log.Message, firstNonEmpty(log.ErrorMessage, log.Message),
|
||||
strings.Join(log.UpdatedCookieNames, ","), log.UpdatedCookieCount, log.ResponseContent)
|
||||
strings.Join(log.UpdatedCookieNames, ","), log.UpdatedCookieCount, log.ResponseContent,
|
||||
log.StepDetails, log.RenewMethod, log.DurationMS, log.RequestCount)
|
||||
return err
|
||||
}
|
||||
|
||||
// CleanupLogs deletes renewal logs older than retentionDays. Non-positive values skip cleanup.
|
||||
func (r *RenewalStore) CleanupLogs(ctx context.Context, retentionDays int) error {
|
||||
if retentionDays <= 0 {
|
||||
return nil
|
||||
}
|
||||
cutoff := time.Now().AddDate(0, 0, -retentionDays)
|
||||
for _, table := range []string{
|
||||
"scheduled_cookies_refresh_log",
|
||||
"scheduled_login_renew_log",
|
||||
"scheduled_api_cookie_renew_log",
|
||||
} {
|
||||
if _, err := r.DB.ExecContext(ctx, `DELETE FROM `+table+` WHERE created_at < ?`, cutoff); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RecentBrowserCookieRenewStatuses 返回最近 limit 条浏览器续期日志状态。
|
||||
func (r *RenewalStore) RecentBrowserCookieRenewStatuses(ctx context.Context, cookieID string, limit int) ([]string, error) {
|
||||
if limit <= 0 {
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
)
|
||||
|
||||
// RiskControlLogs 写入风控处理日志。
|
||||
type RiskControlLogs struct {
|
||||
DB *sql.DB
|
||||
Dialect Dialect
|
||||
}
|
||||
|
||||
// Add 新增一条风控日志,返回自增 ID。
|
||||
func (r *RiskControlLogs) Add(ctx context.Context, log RiskControlLog) (int64, error) {
|
||||
if log.EventType == "" {
|
||||
log.EventType = "slider_captcha"
|
||||
}
|
||||
if log.ProcessingStatus == "" {
|
||||
log.ProcessingStatus = "processing"
|
||||
}
|
||||
return insertReturningID(ctx, r.DB, r.Dialect,
|
||||
`INSERT INTO risk_control_logs
|
||||
(cookie_id, event_type, event_description, processing_result,
|
||||
processing_status, captcha_engine, error_message, duration_ms)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
log.CookieID, log.EventType, log.EventDescription, log.ProcessingResult,
|
||||
log.ProcessingStatus, log.CaptchaEngine, log.ErrorMessage, log.DurationMS)
|
||||
}
|
||||
|
||||
// Update 更新风控日志处理结果。ID 为 0 时安全跳过。
|
||||
func (r *RiskControlLogs) Update(ctx context.Context, id int64, log RiskControlLog) error {
|
||||
if id == 0 {
|
||||
return nil
|
||||
}
|
||||
_, err := r.DB.ExecContext(ctx,
|
||||
`UPDATE risk_control_logs
|
||||
SET processing_result=?, processing_status=?, captcha_engine=?,
|
||||
error_message=?, duration_ms=?, updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=?`,
|
||||
log.ProcessingResult, log.ProcessingStatus, log.CaptchaEngine,
|
||||
log.ErrorMessage, log.DurationMS, id)
|
||||
return err
|
||||
}
|
||||
@@ -24,6 +24,7 @@ type Store struct {
|
||||
Tokens *AccountTokens
|
||||
Renewal *RenewalStore
|
||||
LoginLogs *AccountLoginLogs
|
||||
RiskLogs *RiskControlLogs
|
||||
}
|
||||
|
||||
// NewStore 基于 *sql.DB 构造聚合 store。dialect 用于业务 SQL 方言分支。
|
||||
@@ -49,5 +50,6 @@ func NewStore(db *sql.DB, dialect Dialect) *Store {
|
||||
Tokens: &AccountTokens{DB: db, Dialect: dialect},
|
||||
Renewal: &RenewalStore{DB: db, Dialect: dialect},
|
||||
LoginLogs: &AccountLoginLogs{DB: db},
|
||||
RiskLogs: &RiskControlLogs{DB: db, Dialect: dialect},
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user