合并 main:同步聊天、风控诊断与迁移基线

This commit is contained in:
Christ committed 2026-08-17 21:19:50 +08:00
commit a6c0d36ee9
89 files changed
+2974 -365

No files matched your search

+77 -18
View File
@@ -35,6 +35,8 @@ type ChatMessage struct {
MessageType string `json:"message_type"`
Content string `json:"content"`
Status string `json:"status"`
ReadStatus int `json:"read_status"`
ReadAt int64 `json:"read_at,omitempty"`
SentAt int64 `json:"sent_at"`
}
@@ -156,6 +158,13 @@ func (s *ChatStore) SaveMessage(ctx context.Context, session ChatSession, messag
if message.SentAt <= 0 {
message.SentAt = time.Now().UTC().UnixMilli()
}
// read_status is also used for incoming messages: only a newly received
// real-user message starts unread. Imported history and official system
// notices must never contribute to the chat badge.
if message.Direction == "incoming" && (!unread || message.MessageType == "system") {
message.ReadStatus = 2
message.ReadAt = time.Now().UTC().UnixMilli()
}
message.CookieID, message.ChatID = session.CookieID, session.ChatID
// now 保存now,供当前处理流程使用
now := time.Now().UTC().Unix()
@@ -181,14 +190,14 @@ func (s *ChatStore) SaveMessage(ctx context.Context, session ChatSession, messag
// prefix 保存prefix,供当前处理流程使用
prefix := dialectInsertIgnorePrefix(s.Dialect)
// query 保存查询,供当前处理流程使用
// query 保存带已读字段的幂等插入 SQL,三方言冲突时保持同一列顺序。
query := prefix + ` INTO chat_messages
(cookie_id,chat_id,message_key,direction,sender_id,sender_name,message_type,content,status,sent_at,created_at)
VALUES(?,?,?,?,?,?,?,?,?,?,?)` + dialectInsertIgnore(s.Dialect, []string{"cookie_id", "message_key"})
// res、err 保存res、err,供当前处理流程使用
(cookie_id,chat_id,message_key,direction,sender_id,sender_name,message_type,content,status,read_status,read_at,sent_at,created_at)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)` + dialectInsertIgnore(s.Dialect, []string{"cookie_id", "message_key"})
// res、err 保存插入结果及执行错误,用于判断是否更新会话摘要。
res, err := tx.ExecContext(ctx, query, message.CookieID, message.ChatID, message.MessageKey,
message.Direction, message.SenderID, message.SenderName, message.MessageType, message.Content,
message.Status, message.SentAt, now)
message.Status, message.ReadStatus, message.ReadAt, message.SentAt, now)
if err != nil {
return nil, false, fmt.Errorf("保存聊天消息: %w", err)
}
@@ -222,13 +231,13 @@ func (s *ChatStore) SaveMessage(ctx context.Context, session ChatSession, messag
// GetMessageByKey 读取消息ByKey。
func (s *ChatStore) GetMessageByKey(ctx context.Context, cookieID, key string) (*ChatMessage, error) {
// m 保存m,供当前处理流程使用
// m 保存按账号和幂等键读取的完整聊天消息。
var m ChatMessage
// err 保存err,供当前处理流程使用
err := s.DB.QueryRowContext(ctx, `SELECT id,cookie_id,chat_id,message_key,direction,sender_id,sender_name,message_type,content,status,sent_at
// err 保存查询错误;不存在时转换为仓储统一的 ErrNotFound。
err := s.DB.QueryRowContext(ctx, `SELECT id,cookie_id,chat_id,message_key,direction,sender_id,sender_name,message_type,content,status,read_status,read_at,sent_at
FROM chat_messages WHERE cookie_id=? AND message_key=?`, cookieID, key).Scan(
&m.ID, &m.CookieID, &m.ChatID, &m.MessageKey, &m.Direction, &m.SenderID, &m.SenderName,
&m.MessageType, &m.Content, &m.Status, &m.SentAt)
&m.MessageType, &m.Content, &m.Status, &m.ReadStatus, &m.ReadAt, &m.SentAt)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
@@ -279,8 +288,8 @@ func (s *ChatStore) ListMessages(ctx context.Context, userID int64, cookieID, ch
if limit <= 0 || limit > 200 {
limit = 50
}
// query 保存查询,供当前处理流程使用
query := `SELECT m.id,m.cookie_id,m.chat_id,m.message_key,m.direction,m.sender_id,m.sender_name,m.message_type,m.content,m.status,m.sent_at
// query 保存按时间倒序读取再反转为时间正序的分页 SQL。
query := `SELECT m.id,m.cookie_id,m.chat_id,m.message_key,m.direction,m.sender_id,m.sender_name,m.message_type,m.content,m.status,m.read_status,m.read_at,m.sent_at
FROM chat_messages m JOIN cookies c ON c.id=m.cookie_id
WHERE c.user_id=? AND m.cookie_id=? AND m.chat_id=?`
// args 保存args,供当前处理流程使用
@@ -301,11 +310,11 @@ func (s *ChatStore) ListMessages(ctx context.Context, userID int64, cookieID, ch
// result 保存结果,供当前处理流程使用
var result []ChatMessage
for rows.Next() {
// m 保存m,供当前处理流程使用
// m 保存当前扫描出的消息及其本地已读状态。
var m ChatMessage
if // err 保存err,供当前处理流程使用
err := rows.Scan(&m.ID, &m.CookieID, &m.ChatID, &m.MessageKey, &m.Direction, &m.SenderID,
&m.SenderName, &m.MessageType, &m.Content, &m.Status, &m.SentAt); err != nil {
// err 保存当前行字段映射错误,避免返回缺少已读字段的不完整消息。
if err := rows.Scan(&m.ID, &m.CookieID, &m.ChatID, &m.MessageKey, &m.Direction, &m.SenderID,
&m.SenderName, &m.MessageType, &m.Content, &m.Status, &m.ReadStatus, &m.ReadAt, &m.SentAt); err != nil {
return nil, err
}
result = append(result, m)
@@ -318,15 +327,33 @@ func (s *ChatStore) ListMessages(ctx context.Context, userID int64, cookieID, ch
return result, rows.Err()
}
// MarkRead 负责MarkRead相关处理。
// MarkRead 仅对当前用户拥有账号的非系统入站消息标记已读,并同步归零会话红点。
func (s *ChatStore) MarkRead(ctx context.Context, userID int64, cookieID, chatID string) error {
// err 保存err,供当前处理流程使用
// now 是同一批消息和会话状态使用的统一 UTC 时间,避免页面显示先后矛盾。
now := time.Now().UTC()
// err 保存批量更新非系统入站消息的错误;失败时不得清空会话红点以避免状态不一致。
if _, err := s.DB.ExecContext(ctx, `UPDATE chat_messages SET read_status=2,read_at=?
WHERE cookie_id=? AND chat_id=? AND direction='incoming' AND message_type<>'system' AND read_status<>2`,
now.UnixMilli(), cookieID, chatID); err != nil {
return err
}
// err 保存归零会话红点的错误,该更新通过用户归属子查询阻止越权修改。
_, err := s.DB.ExecContext(ctx, `UPDATE chat_sessions SET unread_count=0,updated_at=?
WHERE cookie_id=? AND chat_id=? AND EXISTS(SELECT 1 FROM cookies c WHERE c.id=chat_sessions.cookie_id AND c.user_id=?)`,
time.Now().UTC().Unix(), cookieID, chatID, userID)
now.Unix(), cookieID, chatID, userID)
return err
}
// CountUnreadUserMessages 返回界面红点使用的入站真实用户未读数,系统消息永不计入。
func (s *ChatStore) CountUnreadUserMessages(ctx context.Context, cookieID, chatID string) (int, error) {
// count 保存符合当前账号、会话及未读条件的消息总数。
var count int
// err 保存聚合查询错误,调用方可在平台响应缺失时退回官方红点值。
err := s.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM chat_messages
WHERE cookie_id=? AND chat_id=? AND direction='incoming' AND message_type<>'system' AND read_status<>2`, cookieID, chatID).Scan(&count)
return count, err
}
// UpdateMessageStatus 更新消息状态。
func (s *ChatStore) UpdateMessageStatus(ctx context.Context, cookieID, key, status string) (*ChatMessage, error) {
if // err 保存err,供当前处理流程使用
@@ -335,3 +362,35 @@ func (s *ChatStore) UpdateMessageStatus(ctx context.Context, cookieID, key, stat
}
return s.GetMessageByKey(ctx, cookieID, key)
}
// MarkMessageRead 按平台回执把一条出站消息标记为已读,并返回更新后的消息。
func (s *ChatStore) MarkMessageRead(ctx context.Context, cookieID, key string, readAt int64) (*ChatMessage, error) {
// readAt 保存平台已读时间;缺失时使用本机 UTC 时间作为展示回退。
if readAt <= 0 {
readAt = time.Now().UTC().UnixMilli()
}
// err 保存只更新出站消息的数据库错误,防止错误改写入站状态。
if _, err := s.DB.ExecContext(ctx, `UPDATE chat_messages SET read_status=2,read_at=? WHERE cookie_id=? AND message_key=? AND direction='outgoing'`, readAt, cookieID, key); err != nil {
return nil, err
}
return s.GetMessageByKey(ctx, cookieID, key)
}
// MarkLatestOutgoingRead 在回执未带消息键时回退标记会话中最近待确认的出站消息。
func (s *ChatStore) MarkLatestOutgoingRead(ctx context.Context, cookieID, chatID string, readAt int64) (*ChatMessage, error) {
// readAt 保存平台已读时间;缺失时使用本机 UTC 时间作为展示回退。
if readAt <= 0 {
readAt = time.Now().UTC().UnixMilli()
}
// key 保存最近一条已发送且未标记已读的消息幂等键。
var key string
// err 保存查询错误;没有可更新消息时返回统一 ErrNotFound。
err := s.DB.QueryRowContext(ctx, `SELECT message_key FROM chat_messages WHERE cookie_id=? AND chat_id=? AND direction='outgoing' AND status='sent' AND read_status<>2 ORDER BY sent_at DESC,id DESC LIMIT 1`, cookieID, chatID).Scan(&key)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
if err != nil {
return nil, err
}
return s.MarkMessageRead(ctx, cookieID, key, readAt)
}
+50 -1
View File
@@ -105,6 +105,53 @@ func TestMigrate_AppliesCleanSchema(t *testing.T) {
db2.Close()
}
// TestMigrate_UpgradesDatabaseWithMainChatVersions 验证已发布 main 的 00029/00030
// 聊天迁移可以原样升级到合并后的 dev 最终版本。
func TestMigrate_UpgradesDatabaseWithMainChatVersions(t *testing.T) {
// tmpDir 保存隔离的已发布 main 数据库目录,测试结束后由 testing 清理。
tmpDir := t.TempDir()
// dbPath 指向模拟已运行至 main 00030 的 SQLite 文件。
dbPath := filepath.Join(tmpDir, "main-chat-v30.db")
// rawDB 在调用 Open 前控制 Goose 只执行已发布的 main 迁移。
rawDB, openErr := sql.Open("sqlite", sqliteDSN(dbPath))
if openErr != nil {
t.Fatalf("open legacy database: %v", openErr)
}
defer rawDB.Close()
// dialectErr 保存 Goose SQLite 方言设置失败,失败时不能构造已发布迁移基线。
if dialectErr := goose.SetDialect("sqlite3"); dialectErr != nil {
t.Fatalf("set goose dialect: %v", dialectErr)
}
goose.SetBaseFS(migrationsFS)
// upErr 将数据库推进到已发布 main 的 00030,验证之后的 dev 迁移连续接续。
upErr := goose.UpTo(rawDB, "migrations/sqlite", 30)
if upErr != nil {
t.Fatalf("apply released main migrations: %v", upErr)
}
// ctx 提供迁移 API 所需的调用上下文;升级本身不依赖请求生命周期。
ctx := context.Background()
// migrateErr 保存从 main 00030 接续 dev 00031 时的迁移失败。
if migrateErr := Migrate(ctx, rawDB, DialectSQLite); migrateErr != nil {
t.Fatalf("upgrade from main 00030: %v", migrateErr)
}
if !tableExists(t, rawDB, "order_reconciliations") {
t.Fatal("order_reconciliations should be created by the dev schema baseline migration")
}
if !columnExists(t, rawDB, "chat_messages", "read_status") || !columnExists(t, rawDB, "chat_messages", "read_at") {
t.Fatal("chat read tracking columns should remain after dev schema baseline upgrade")
}
// finalVersion 验证迁移账本已推进到合并后的单一 dev schema 基线版本。
finalVersion, versionErr := goose.GetDBVersion(rawDB)
if versionErr != nil {
t.Fatalf("read final migration version: %v", versionErr)
}
if finalVersion != 31 {
t.Fatalf("final migration version=%d, want 31", finalVersion)
}
}
// columnExists 负责columnExists相关处理。
func columnExists(t *testing.T, db *sql.DB, table, col string) bool {
t.Helper()
@@ -156,7 +203,7 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) {
}
// i 表示本次回滚操作序号。
for i := 0; version >= 14; i++ {
if // err 保存err,供当前处理流程使用
if // err 保存当前迁移回滚错误,任一方言步骤失败即终止验证。
err := goose.Down(d, "migrations/sqlite"); err != nil {
t.Fatalf("down migration #%d: %v", i+1, err)
}
@@ -220,6 +267,8 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) {
{"account_task_runs", "run_key"},
{"chat_sessions", "unread_count"},
{"chat_messages", "message_key"},
{"chat_messages", "read_status"},
{"chat_messages", "read_at"},
{"notification_outbox", "uncertain_at"},
} {
if !columnExists(t, d, c.table, c.col) {
@@ -0,0 +1,6 @@
-- +goose Up
ALTER TABLE chat_messages ADD COLUMN read_status INT NOT NULL DEFAULT 0;
ALTER TABLE chat_messages ADD COLUMN read_at BIGINT NOT NULL DEFAULT 0;
-- +goose Down
ALTER TABLE chat_messages DROP COLUMN read_at;
ALTER TABLE chat_messages DROP COLUMN read_status;
@@ -1,16 +0,0 @@
-- +goose Up
CREATE TABLE IF NOT EXISTS order_reconciliations (
id VARCHAR(36) PRIMARY KEY,
order_id VARCHAR(255) NOT NULL,
cookie_id VARCHAR(255) NOT NULL,
kind VARCHAR(100) NOT NULL,
status VARCHAR(32) NOT NULL DEFAULT 'pending',
error_message TEXT NOT NULL,
attempts INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_order_reconciliations_pending (status, created_at, id)
);
-- +goose Down
DROP TABLE IF EXISTS order_reconciliations;
@@ -0,0 +1,6 @@
-- +goose Up
UPDATE chat_messages SET read_status=2, read_at=CASE WHEN read_at=0 THEN UNIX_TIMESTAMP(CURRENT_TIMESTAMP) * 1000 ELSE read_at END
WHERE direction='incoming' AND read_status=0;
-- +goose Down
-- No safe reverse: the previous schema had no per-message read boundary.
@@ -1,5 +0,0 @@
-- +goose Up
CREATE INDEX idx_orders_cursor ON orders(cookie_id, deleted_at, created_at DESC, order_id DESC);
-- +goose Down
DROP INDEX idx_orders_cursor ON orders;
@@ -0,0 +1,57 @@
-- +goose Up
CREATE TABLE IF NOT EXISTS order_reconciliations (
id VARCHAR(36) PRIMARY KEY,
order_id VARCHAR(255) NOT NULL,
cookie_id VARCHAR(255) NOT NULL,
kind VARCHAR(100) NOT NULL,
status VARCHAR(32) NOT NULL DEFAULT 'pending',
error_message TEXT NOT NULL,
attempts INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_order_reconciliations_pending (status, created_at, id)
);
CREATE INDEX idx_orders_cursor ON orders(cookie_id, deleted_at, created_at DESC, order_id DESC);
CREATE TABLE IF NOT EXISTS order_refresh_jobs (
id VARCHAR(64) PRIMARY KEY,
user_id BIGINT NOT NULL,
cookie_id VARCHAR(255) NOT NULL DEFAULT '',
filter_status VARCHAR(64) NOT NULL DEFAULT '',
status VARCHAR(32) NOT NULL DEFAULT 'queued',
result_json LONGTEXT NOT NULL,
error_message TEXT NOT NULL,
worker_token VARCHAR(128) NOT NULL DEFAULT '',
lease_expires_at BIGINT NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT fk_order_refresh_jobs_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
INDEX idx_order_refresh_jobs_user (user_id, created_at, id),
INDEX idx_order_refresh_jobs_lease (status, lease_expires_at)
);
CREATE TABLE IF NOT EXISTS security_audit_logs (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
user_id BIGINT NOT NULL,
action VARCHAR(128) NOT NULL,
resource VARCHAR(255) NOT NULL,
keys_json TEXT NOT NULL,
outcome VARCHAR(32) NOT NULL DEFAULT 'accepted',
created_at BIGINT NOT NULL,
INDEX idx_security_audit_logs_user_created (user_id, created_at, id)
);
ALTER TABLE notification_outbox ADD COLUMN uncertain_at BIGINT NOT NULL DEFAULT 0;
ALTER TABLE notification_outbox ADD COLUMN idempotency_key VARCHAR(255) NULL;
CREATE UNIQUE INDEX idx_notification_outbox_channel_idempotency
ON notification_outbox(channel_id, idempotency_key);
-- +goose Down
DROP INDEX idx_notification_outbox_channel_idempotency ON notification_outbox;
ALTER TABLE notification_outbox DROP COLUMN idempotency_key;
ALTER TABLE notification_outbox DROP COLUMN uncertain_at;
DROP TABLE IF EXISTS security_audit_logs;
DROP TABLE IF EXISTS order_refresh_jobs;
DROP INDEX idx_orders_cursor ON orders;
DROP TABLE IF EXISTS order_reconciliations;
@@ -1,20 +0,0 @@
-- +goose Up
CREATE TABLE IF NOT EXISTS order_refresh_jobs (
id VARCHAR(64) PRIMARY KEY,
user_id BIGINT NOT NULL,
cookie_id VARCHAR(255) NOT NULL DEFAULT '',
filter_status VARCHAR(64) NOT NULL DEFAULT '',
status VARCHAR(32) NOT NULL DEFAULT 'queued',
result_json LONGTEXT NOT NULL,
error_message TEXT NOT NULL,
worker_token VARCHAR(128) NOT NULL DEFAULT '',
lease_expires_at BIGINT NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT fk_order_refresh_jobs_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
INDEX idx_order_refresh_jobs_user (user_id, created_at, id),
INDEX idx_order_refresh_jobs_lease (status, lease_expires_at)
);
-- +goose Down
DROP TABLE IF EXISTS order_refresh_jobs;
@@ -1,14 +0,0 @@
-- +goose Up
CREATE TABLE IF NOT EXISTS security_audit_logs (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
user_id BIGINT NOT NULL,
action VARCHAR(128) NOT NULL,
resource VARCHAR(255) NOT NULL,
keys_json TEXT NOT NULL,
outcome VARCHAR(32) NOT NULL DEFAULT 'accepted',
created_at BIGINT NOT NULL,
INDEX idx_security_audit_logs_user_created (user_id, created_at, id)
);
-- +goose Down
DROP TABLE IF EXISTS security_audit_logs;
@@ -1,6 +0,0 @@
-- +goose Up
-- uncertain_at 记录外部发送成功但本地确认失败的隔离时间,避免租约过期后自动重复发送。
ALTER TABLE notification_outbox ADD COLUMN uncertain_at BIGINT NOT NULL DEFAULT 0;
-- +goose Down
ALTER TABLE notification_outbox DROP COLUMN uncertain_at;
@@ -1,10 +0,0 @@
-- +goose Up
-- idempotency_key 让同一自动化运行终态对同一渠道只保留一条 outbox 记录。
-- NULL 保持历史普通通知可重复投递;uncertain 记录保留原键,从而禁止恢复时自动重新入队。
ALTER TABLE notification_outbox ADD COLUMN idempotency_key VARCHAR(255) NULL;
CREATE UNIQUE INDEX idx_notification_outbox_channel_idempotency
ON notification_outbox(channel_id, idempotency_key);
-- +goose Down
DROP INDEX idx_notification_outbox_channel_idempotency ON notification_outbox;
ALTER TABLE notification_outbox DROP COLUMN idempotency_key;
@@ -0,0 +1,6 @@
-- +goose Up
ALTER TABLE chat_messages ADD COLUMN read_status INTEGER NOT NULL DEFAULT 0;
ALTER TABLE chat_messages ADD COLUMN read_at BIGINT NOT NULL DEFAULT 0;
-- +goose Down
ALTER TABLE chat_messages DROP COLUMN read_at;
ALTER TABLE chat_messages DROP COLUMN read_status;
@@ -1,17 +0,0 @@
-- +goose Up
CREATE TABLE IF NOT EXISTS order_reconciliations (
id TEXT PRIMARY KEY,
order_id TEXT NOT NULL,
cookie_id TEXT NOT NULL,
kind TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
error_message TEXT NOT NULL DEFAULT '',
attempts INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_order_reconciliations_pending
ON order_reconciliations(status, created_at, id);
-- +goose Down
DROP TABLE IF EXISTS order_reconciliations;
@@ -0,0 +1,6 @@
-- +goose Up
UPDATE chat_messages SET read_status=2, read_at=CASE WHEN read_at=0 THEN (EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000)::BIGINT ELSE read_at END
WHERE direction='incoming' AND read_status=0;
-- +goose Down
-- No safe reverse: the previous schema had no per-message read boundary.
@@ -1,5 +0,0 @@
-- +goose Up
CREATE INDEX IF NOT EXISTS idx_orders_cursor ON orders(cookie_id, deleted_at, created_at DESC, order_id DESC);
-- +goose Down
DROP INDEX IF EXISTS idx_orders_cursor;
@@ -0,0 +1,60 @@
-- +goose Up
CREATE TABLE IF NOT EXISTS order_reconciliations (
id TEXT PRIMARY KEY,
order_id TEXT NOT NULL,
cookie_id TEXT NOT NULL,
kind TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
error_message TEXT NOT NULL DEFAULT '',
attempts INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_order_reconciliations_pending
ON order_reconciliations(status, created_at, id);
CREATE INDEX IF NOT EXISTS idx_orders_cursor ON orders(cookie_id, deleted_at, created_at DESC, order_id DESC);
CREATE TABLE IF NOT EXISTS order_refresh_jobs (
id TEXT PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
cookie_id TEXT NOT NULL DEFAULT '',
filter_status TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL DEFAULT 'queued',
result_json TEXT NOT NULL DEFAULT '{}',
error_message TEXT NOT NULL DEFAULT '',
worker_token TEXT NOT NULL DEFAULT '',
lease_expires_at BIGINT NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_order_refresh_jobs_user ON order_refresh_jobs(user_id, created_at DESC, id DESC);
CREATE INDEX IF NOT EXISTS idx_order_refresh_jobs_lease ON order_refresh_jobs(status, lease_expires_at);
CREATE TABLE IF NOT EXISTS security_audit_logs (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL,
action VARCHAR(128) NOT NULL,
resource VARCHAR(255) NOT NULL,
keys_json TEXT NOT NULL DEFAULT '[]',
outcome VARCHAR(32) NOT NULL DEFAULT 'accepted',
created_at BIGINT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_security_audit_logs_user_created
ON security_audit_logs(user_id, created_at DESC, id DESC);
ALTER TABLE notification_outbox ADD COLUMN uncertain_at BIGINT NOT NULL DEFAULT 0;
ALTER TABLE notification_outbox ADD COLUMN idempotency_key TEXT NULL;
CREATE UNIQUE INDEX idx_notification_outbox_channel_idempotency
ON notification_outbox(channel_id, idempotency_key);
-- +goose Down
DROP INDEX IF EXISTS idx_notification_outbox_channel_idempotency;
ALTER TABLE notification_outbox DROP COLUMN idempotency_key;
ALTER TABLE notification_outbox DROP COLUMN uncertain_at;
DROP TABLE IF EXISTS security_audit_logs;
DROP INDEX IF EXISTS idx_order_refresh_jobs_lease;
DROP INDEX IF EXISTS idx_order_refresh_jobs_user;
DROP TABLE IF EXISTS order_refresh_jobs;
DROP INDEX IF EXISTS idx_orders_cursor;
DROP TABLE IF EXISTS order_reconciliations;
@@ -1,21 +0,0 @@
-- +goose Up
CREATE TABLE IF NOT EXISTS order_refresh_jobs (
id TEXT PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
cookie_id TEXT NOT NULL DEFAULT '',
filter_status TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL DEFAULT 'queued',
result_json TEXT NOT NULL DEFAULT '{}',
error_message TEXT NOT NULL DEFAULT '',
worker_token TEXT NOT NULL DEFAULT '',
lease_expires_at BIGINT NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_order_refresh_jobs_user ON order_refresh_jobs(user_id, created_at DESC, id DESC);
CREATE INDEX IF NOT EXISTS idx_order_refresh_jobs_lease ON order_refresh_jobs(status, lease_expires_at);
-- +goose Down
DROP INDEX IF EXISTS idx_order_refresh_jobs_lease;
DROP INDEX IF EXISTS idx_order_refresh_jobs_user;
DROP TABLE IF EXISTS order_refresh_jobs;
@@ -1,16 +0,0 @@
-- +goose Up
CREATE TABLE IF NOT EXISTS security_audit_logs (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL,
action VARCHAR(128) NOT NULL,
resource VARCHAR(255) NOT NULL,
keys_json TEXT NOT NULL DEFAULT '[]',
outcome VARCHAR(32) NOT NULL DEFAULT 'accepted',
created_at BIGINT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_security_audit_logs_user_created
ON security_audit_logs(user_id, created_at DESC, id DESC);
-- +goose Down
DROP TABLE IF EXISTS security_audit_logs;
@@ -1,6 +0,0 @@
-- +goose Up
-- uncertain_at 记录外部发送成功但本地确认失败的隔离时间,避免租约过期后自动重复发送。
ALTER TABLE notification_outbox ADD COLUMN uncertain_at BIGINT NOT NULL DEFAULT 0;
-- +goose Down
ALTER TABLE notification_outbox DROP COLUMN uncertain_at;
@@ -1,10 +0,0 @@
-- +goose Up
-- idempotency_key 让同一自动化运行终态对同一渠道只保留一条 outbox 记录。
-- NULL 保持历史普通通知可重复投递;uncertain 记录保留原键,从而禁止恢复时自动重新入队。
ALTER TABLE notification_outbox ADD COLUMN idempotency_key TEXT NULL;
CREATE UNIQUE INDEX idx_notification_outbox_channel_idempotency
ON notification_outbox(channel_id, idempotency_key);
-- +goose Down
DROP INDEX IF EXISTS idx_notification_outbox_channel_idempotency;
ALTER TABLE notification_outbox DROP COLUMN idempotency_key;
@@ -0,0 +1,6 @@
-- +goose Up
ALTER TABLE chat_messages ADD COLUMN read_status INTEGER NOT NULL DEFAULT 0;
ALTER TABLE chat_messages ADD COLUMN read_at INTEGER NOT NULL DEFAULT 0;
-- +goose Down
ALTER TABLE chat_messages DROP COLUMN read_at;
ALTER TABLE chat_messages DROP COLUMN read_status;
@@ -1,17 +0,0 @@
-- +goose Up
CREATE TABLE IF NOT EXISTS order_reconciliations (
id TEXT PRIMARY KEY,
order_id TEXT NOT NULL,
cookie_id TEXT NOT NULL,
kind TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
error_message TEXT NOT NULL DEFAULT '',
attempts INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_order_reconciliations_pending
ON order_reconciliations(status, created_at, id);
-- +goose Down
DROP TABLE IF EXISTS order_reconciliations;
@@ -0,0 +1,8 @@
-- +goose Up
-- Messages already stored before message-level read tracking was introduced
-- are history snapshots, not newly received unread messages.
UPDATE chat_messages SET read_status=2, read_at=CASE WHEN read_at=0 THEN strftime('%s','now') * 1000 ELSE read_at END
WHERE direction='incoming' AND read_status=0;
-- +goose Down
-- No safe reverse: the previous schema had no per-message read boundary.
@@ -1,5 +0,0 @@
-- +goose Up
CREATE INDEX IF NOT EXISTS idx_orders_cursor ON orders(cookie_id, deleted_at, created_at DESC, order_id DESC);
-- +goose Down
DROP INDEX IF EXISTS idx_orders_cursor;
@@ -0,0 +1,60 @@
-- +goose Up
CREATE TABLE IF NOT EXISTS order_reconciliations (
id TEXT PRIMARY KEY,
order_id TEXT NOT NULL,
cookie_id TEXT NOT NULL,
kind TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
error_message TEXT NOT NULL DEFAULT '',
attempts INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_order_reconciliations_pending
ON order_reconciliations(status, created_at, id);
CREATE INDEX IF NOT EXISTS idx_orders_cursor ON orders(cookie_id, deleted_at, created_at DESC, order_id DESC);
CREATE TABLE IF NOT EXISTS order_refresh_jobs (
id TEXT PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
cookie_id TEXT NOT NULL DEFAULT '',
filter_status TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL DEFAULT 'queued',
result_json TEXT NOT NULL DEFAULT '{}',
error_message TEXT NOT NULL DEFAULT '',
worker_token TEXT NOT NULL DEFAULT '',
lease_expires_at INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_order_refresh_jobs_user ON order_refresh_jobs(user_id, created_at DESC, id DESC);
CREATE INDEX IF NOT EXISTS idx_order_refresh_jobs_lease ON order_refresh_jobs(status, lease_expires_at);
CREATE TABLE IF NOT EXISTS security_audit_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
action TEXT NOT NULL,
resource TEXT NOT NULL,
keys_json TEXT NOT NULL DEFAULT '[]',
outcome TEXT NOT NULL DEFAULT 'accepted',
created_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_security_audit_logs_user_created
ON security_audit_logs(user_id, created_at DESC, id DESC);
ALTER TABLE notification_outbox ADD COLUMN uncertain_at INTEGER NOT NULL DEFAULT 0;
ALTER TABLE notification_outbox ADD COLUMN idempotency_key TEXT NULL;
CREATE UNIQUE INDEX idx_notification_outbox_channel_idempotency
ON notification_outbox(channel_id, idempotency_key);
-- +goose Down
DROP INDEX IF EXISTS idx_notification_outbox_channel_idempotency;
ALTER TABLE notification_outbox DROP COLUMN idempotency_key;
ALTER TABLE notification_outbox DROP COLUMN uncertain_at;
DROP TABLE IF EXISTS security_audit_logs;
DROP INDEX IF EXISTS idx_order_refresh_jobs_lease;
DROP INDEX IF EXISTS idx_order_refresh_jobs_user;
DROP TABLE IF EXISTS order_refresh_jobs;
DROP INDEX IF EXISTS idx_orders_cursor;
DROP TABLE IF EXISTS order_reconciliations;
@@ -1,21 +0,0 @@
-- +goose Up
CREATE TABLE IF NOT EXISTS order_refresh_jobs (
id TEXT PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
cookie_id TEXT NOT NULL DEFAULT '',
filter_status TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL DEFAULT 'queued',
result_json TEXT NOT NULL DEFAULT '{}',
error_message TEXT NOT NULL DEFAULT '',
worker_token TEXT NOT NULL DEFAULT '',
lease_expires_at INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_order_refresh_jobs_user ON order_refresh_jobs(user_id, created_at DESC, id DESC);
CREATE INDEX IF NOT EXISTS idx_order_refresh_jobs_lease ON order_refresh_jobs(status, lease_expires_at);
-- +goose Down
DROP INDEX IF EXISTS idx_order_refresh_jobs_lease;
DROP INDEX IF EXISTS idx_order_refresh_jobs_user;
DROP TABLE IF EXISTS order_refresh_jobs;
@@ -1,16 +0,0 @@
-- +goose Up
CREATE TABLE IF NOT EXISTS security_audit_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
action TEXT NOT NULL,
resource TEXT NOT NULL,
keys_json TEXT NOT NULL DEFAULT '[]',
outcome TEXT NOT NULL DEFAULT 'accepted',
created_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_security_audit_logs_user_created
ON security_audit_logs(user_id, created_at DESC, id DESC);
-- +goose Down
DROP TABLE IF EXISTS security_audit_logs;
@@ -1,6 +0,0 @@
-- +goose Up
-- uncertain_at 记录外部发送成功但本地确认失败的隔离时间,避免租约过期后自动重复发送。
ALTER TABLE notification_outbox ADD COLUMN uncertain_at INTEGER NOT NULL DEFAULT 0;
-- +goose Down
ALTER TABLE notification_outbox DROP COLUMN uncertain_at;
@@ -1,10 +0,0 @@
-- +goose Up
-- idempotency_key 让同一自动化运行终态对同一渠道只保留一条 outbox 记录。
-- NULL 保持历史普通通知可重复投递;uncertain 记录保留原键,从而禁止恢复时自动重新入队。
ALTER TABLE notification_outbox ADD COLUMN idempotency_key TEXT NULL;
CREATE UNIQUE INDEX idx_notification_outbox_channel_idempotency
ON notification_outbox(channel_id, idempotency_key);
-- +goose Down
DROP INDEX IF EXISTS idx_notification_outbox_channel_idempotency;
ALTER TABLE notification_outbox DROP COLUMN idempotency_key;
+3 -1
View File
@@ -1222,7 +1222,7 @@ func TestMultiDB_LatestMigrationsDownUp(t *testing.T) {
}
// i 表示本次回滚操作序号。
for i := 0; version >= 14; i++ {
if // err 保存err,供当前处理流程使用
if // err 保存当前方言迁移回滚错误,失败时保留步骤号诊断。
err := goose.Down(tg.store.DB, "migrations/"+subdir); err != nil {
t.Fatalf("migration down #%d: %v", i+1, err)
}
@@ -1285,6 +1285,8 @@ func TestMultiDB_LatestMigrationsDownUp(t *testing.T) {
{"account_task_runs", "run_key"},
{"chat_sessions", "unread_count"},
{"chat_messages", "message_key"},
{"chat_messages", "read_status"},
{"chat_messages", "read_at"},
} {
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)
+29
View File
@@ -68,3 +68,32 @@ func (w *WSMessageStore) DeleteBefore(ctx context.Context, cookieID string, cuto
}
return result.RowsAffected()
}
// FindInboundParsedJSONContaining 返回最近的已解密入站诊断帧,供旧版聊天消息标识迁移使用。
func (w *WSMessageStore) FindInboundParsedJSONContaining(ctx context.Context, cookieID, fragment string, limit int) ([]string, error) {
// safeLimit 限制诊断查询行数,避免单次已读操作读取过多历史帧。
safeLimit := limit
if safeLimit <= 0 || safeLimit > 100 {
safeLimit = 20
}
// rows、err 保存匹配的诊断帧游标及数据库查询错误。
rows, err := w.DB.QueryContext(ctx, `SELECT parsed_json FROM ws_messages
WHERE cookie_id=? AND direction='in' AND parse_status='decrypted' AND parsed_json LIKE ?
ORDER BY id DESC LIMIT ?`, cookieID, "%"+fragment+"%", safeLimit)
if err != nil {
return nil, err
}
defer rows.Close()
// values 保存按时间倒序读取的已解密诊断 JSON。
values := make([]string, 0, safeLimit)
for rows.Next() {
// value 保存当前诊断帧的解析 JSON。
var value string
// scanErr 保存当前诊断帧字段扫描错误。
if scanErr := rows.Scan(&value); scanErr != nil {
return nil, scanErr
}
values = append(values, value)
}
return values, rows.Err()
}