package librarymaintenance import ( "bufio" "context" "errors" "fmt" "net" "strconv" "strings" "time" "github.com/jackc/pgx/v5/pgxpool" ) // targetQuiescer 回答"后台写入者是不是已经空了": // - 目标库:未结清的后台操作、未完成的解析(这两张表就是 app 的后台账本); // - 目标队列:asynq 里还在排队/在跑/待重试的任务。 // // 为什么要单独做:HTTP 入口排空只覆盖连接;app 内的 asynq worker 会被上游的 // SIGTERM exit(1) 切断,正在跑的任务就这样被腰斩。窗口必须先等它们结束。 type targetQuiescer struct { pool *pgxpool.Pool redisAddr string redisPass string redisDB int timeout time.Duration queueMatch string } func newTargetQuiescer(ctx context.Context, databaseURL, redisAddr, redisPass string, redisDB int, timeout time.Duration) (*targetQuiescer, error) { if databaseURL == "" || redisAddr == "" { return nil, errors.New("后台静默检查缺少目标库或队列地址") } pool, err := pgxpool.New(ctx, databaseURL) if err != nil { return nil, errors.New("后台静默检查连不上目标库") } if timeout <= 0 { timeout = 10 * time.Second } return &targetQuiescer{pool: pool, redisAddr: redisAddr, redisPass: redisPass, redisDB: redisDB, timeout: timeout, queueMatch: "asynq:*"}, nil } func (q *targetQuiescer) Close() { q.pool.Close() } func (q *targetQuiescer) Idle(ctx context.Context) (bool, string, error) { var pendingOps, unsettled int64 // task_pending_ops / knowledges 是 app 自己的后台账本:不看它们只看 HTTP 会漏。 if err := q.pool.QueryRow(ctx, `SELECT (SELECT count(*) FROM task_pending_ops), (SELECT count(*) FROM knowledges WHERE deleted_at IS NULL AND (parse_status IS DISTINCT FROM 'completed' OR pending_subtasks_count IS NULL OR pending_subtasks_count<>0))`). Scan(&pendingOps, &unsettled); err != nil { return false, "", fmt.Errorf("读不到后台账本:%w", err) } depth, err := q.queueDepth(ctx) if err != nil { return false, "", err } detail := fmt.Sprintf("pending_ops=%d unsettled_knowledges=%d asynq_active=%d", pendingOps, unsettled, depth) return pendingOps == 0 && unsettled == 0 && depth == 0, detail, nil } // queueDepth 统计 asynq 里"还没结束"的任务数(排队/在跑/待重试)。 // archived/completed 是历史,不算忙。 func (q *targetQuiescer) queueDepth(ctx context.Context) (int64, error) { conn, err := dialRedis(q.redisAddr, q.redisPass, q.redisDB, q.timeout) if err != nil { return 0, fmt.Errorf("连不上目标队列:%w", err) } defer conn.Close() keys, err := conn.scan(ctx, q.queueMatch) if err != nil { return 0, fmt.Errorf("扫描目标队列失败:%w", err) } var total int64 for _, key := range keys { suffix := key[strings.LastIndex(key, ":"):] switch suffix { case ":pending", ":active", ":inprogress": n, err := conn.intCmd(ctx, "LLEN", key) if err != nil { return 0, err } total += n case ":scheduled", ":retry": n, err := conn.intCmd(ctx, "ZCARD", key) if err != nil { return 0, err } total += n } } return total, nil } // ---- 最小 RESP 客户端:只用到 AUTH/SELECT/SCAN/LLEN/ZCARD,不引第三方库 ---- type redisConn struct { conn net.Conn reader *bufio.Reader timeout time.Duration } func dialRedis(addr, password string, db int, timeout time.Duration) (*redisConn, error) { dialer := &net.Dialer{Timeout: timeout} conn, err := dialer.Dial("tcp", addr) if err != nil { return nil, err } _ = conn.SetDeadline(time.Now().Add(timeout)) c := &redisConn{conn: conn, reader: bufio.NewReader(conn), timeout: timeout} if password != "" { if _, err := c.do("AUTH", password); err != nil { conn.Close() return nil, err } } if db != 0 { if _, err := c.do("SELECT", strconv.Itoa(db)); err != nil { conn.Close() return nil, err } } return c, nil } func (c *redisConn) Close() error { return c.conn.Close() } func (c *redisConn) do(args ...string) (any, error) { _ = c.conn.SetDeadline(time.Now().Add(c.timeout)) var builder strings.Builder builder.WriteString("*" + strconv.Itoa(len(args)) + "\r\n") for _, arg := range args { builder.WriteString("$" + strconv.Itoa(len(arg)) + "\r\n" + arg + "\r\n") } if _, err := c.conn.Write([]byte(builder.String())); err != nil { return nil, err } return c.read() } func (c *redisConn) read() (any, error) { line, err := c.reader.ReadString('\n') if err != nil { return nil, err } line = strings.TrimRight(line, "\r\n") if line == "" { return nil, errors.New("empty redis reply") } switch line[0] { case '+': return line[1:], nil case '-': return nil, errors.New(line[1:]) case ':': value, err := strconv.ParseInt(line[1:], 10, 64) return value, err case '$': length, err := strconv.Atoi(line[1:]) if err != nil { return nil, err } if length < 0 { return nil, nil } buf := make([]byte, length+2) if _, err := ioReadFull(c.reader, buf); err != nil { return nil, err } return string(buf[:length]), nil case '*': count, err := strconv.Atoi(line[1:]) if err != nil { return nil, err } items := make([]any, 0, count) for i := 0; i < count; i++ { item, err := c.read() if err != nil { return nil, err } items = append(items, item) } return items, nil default: return nil, errors.New("unsupported redis reply") } } func ioReadFull(reader *bufio.Reader, buf []byte) (int, error) { total := 0 for total < len(buf) { n, err := reader.Read(buf[total:]) total += n if err != nil { return total, err } } return total, nil } func (c *redisConn) scan(ctx context.Context, match string) ([]string, error) { var keys []string cursor := "0" for { if err := ctx.Err(); err != nil { return nil, err } reply, err := c.do("SCAN", cursor, "MATCH", match, "COUNT", "1000") if err != nil { return nil, err } items, ok := reply.([]any) if !ok || len(items) != 2 { return nil, errors.New("unexpected SCAN reply") } next, _ := items[0].(string) batch, _ := items[1].([]any) for _, item := range batch { if key, ok := item.(string); ok { keys = append(keys, key) } } if next == "0" || next == "" { return keys, nil } cursor = next } } func (c *redisConn) intCmd(ctx context.Context, cmd string, args ...string) (int64, error) { if err := ctx.Err(); err != nil { return 0, err } reply, err := c.do(append([]string{cmd}, args...)...) if err != nil { return 0, err } value, ok := reply.(int64) if !ok { return 0, errors.New("unexpected integer reply") } return value, nil }