Files
Losita 61db646805 Version: 0.9.80.dev.260506
后端:
1. LLM 独立服务与统一计费出口落地:新增 `cmd/llm`、`client/llm` 与 `services/llm/rpc`,补齐 BillingContext、CreditBalanceGuard、价格规则解析、stream usage 归集与 `credit.charge.requested` outbox 发布,active-scheduler / agent / course / memory / gateway fallback 全部改走 llm zrpc,不再各自本地初始化模型。
2. TokenStore 收口为 Credit 权威账本:新增 credit account / ledger / product / order / price-rule / reward-rule 能力与 Redis 快照缓存,扩展 tokenstore rpc/client 支撑余额快照、消耗看板、商品、订单、流水、价格规则和奖励规则,并接入 LLM charge 事件消费完成 Credit 扣费落账。
3. 计费旧链路下线与网关切口切换:`/token-store` 语义整体切到 `/credit-store`,agent chat 移除旧 TokenQuotaGuard,userauth 的 CheckTokenQuota / AdjustTokenUsage 改为废弃,聊天历史落库不再同步旧 token 额度账本,course 图片解析请求补 user_id 进入新计费口径。

前端:
4. 计划广场从 mock 数据切到真实接口:新增 forum api/types,首页支持真实列表、标签、搜索、防抖、点赞、导入和发布计划,详情页补齐帖子详情、评论树、回复和删除评论链路,同时补上“至少一个标签”的前后端约束与默认标签兜底。
5. 商店页切到 Credit 体系并重做展示:顶部改为余额 + Credit/Token 消耗看板,支持 24h/7d/30d/all 周期切换;套餐区展示原价与当前价;历史区改为当前用户 Credit 流水并支持查看更多,整体视觉和交互同步收口。

仓库:
6. 配置与本地启动体系补齐 llm / outbox 编排:`config.example.yaml` 增加 llm rpc 和统一 outbox service 配置,`dev-common.ps1` 把 llm 纳入多服务依赖并自动建 Kafka topic,`docker-compose.yml` 同步初始化 agent/task/memory/active-scheduler/notification/taskclass-forum/llm/token-store 全量 outbox topic。
2026-05-06 20:16:53 +08:00

165 lines
4.7 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package course
import (
"context"
"encoding/json"
"errors"
"strings"
"time"
coursepb "github.com/LoveLosita/smartflow/backend/services/course/rpc/pb"
coursecontracts "github.com/LoveLosita/smartflow/backend/shared/contracts/course"
"github.com/zeromicro/go-zero/zrpc"
"google.golang.org/grpc"
)
const (
defaultEndpoint = "127.0.0.1:9087"
// 课表导入可能一次展开大量周次与节次RPC 默认超时与网关保持一致,避免内层先被截断。
defaultTimeout = 5 * time.Minute
defaultMaxRPCMessageSize = 8 * 1024 * 1024
rpcMessageSizePadding = 1024 * 1024
)
type ClientConfig struct {
Endpoints []string
Target string
Timeout time.Duration
MaxImageBytes int64
}
// Client 是 gateway 访问 course zrpc 的最小适配层。
//
// 职责边界:
// 1. 只负责跨进程 gRPC 调用和 JSON/bytes 透传,不触碰 DAO
// 2. HTTP 入参仍由 gateway/api 做基础绑定,业务校验交给 course 服务;
// 3. import 冲突通过 CourseImportConflictError 返回,让 HTTP 层保留 409 + conflicts 数据。
type Client struct {
rpc coursepb.CourseClient
}
func NewClient(cfg ClientConfig) (*Client, error) {
timeout := cfg.Timeout
if timeout <= 0 {
timeout = defaultTimeout
}
endpoints := normalizeEndpoints(cfg.Endpoints)
target := strings.TrimSpace(cfg.Target)
if len(endpoints) == 0 && target == "" {
endpoints = []string{defaultEndpoint}
}
maxMessageSize := normalizeMaxRPCMessageSize(cfg.MaxImageBytes)
zclient, err := zrpc.NewClient(zrpc.RpcClientConf{
Endpoints: endpoints,
Target: target,
NonBlock: true,
Timeout: int64(timeout / time.Millisecond),
}, zrpc.WithDialOption(grpc.WithDefaultCallOptions(
grpc.MaxCallRecvMsgSize(maxMessageSize),
grpc.MaxCallSendMsgSize(maxMessageSize),
)))
if err != nil {
return nil, err
}
client := &Client{rpc: coursepb.NewCourseClient(zclient.Conn())}
if err := client.ping(timeout); err != nil {
return nil, err
}
return client, nil
}
func (c *Client) ValidateCourse(ctx context.Context, req coursecontracts.UserCheckCourseRequest) error {
_, err := c.callJSON(ctx, c.rpc.ValidateCourse, req)
return responseFromRPCError(err)
}
func (c *Client) ImportCourses(ctx context.Context, req coursecontracts.UserImportCoursesRequest) (json.RawMessage, error) {
resp, err := c.callJSON(ctx, c.rpc.ImportCourses, req)
raw, err := jsonFromResponse(resp, err)
if err != nil {
return nil, err
}
var result coursecontracts.ImportCoursesResult
if err := json.Unmarshal(raw, &result); err != nil {
return nil, err
}
if result.Conflict {
return nil, CourseImportConflictError{conflicts: result.Conflicts}
}
return raw, nil
}
func (c *Client) ParseCourseTableImage(ctx context.Context, req coursecontracts.CourseImageParseRequest) (json.RawMessage, error) {
resp, err := c.rpc.ParseCourseImage(ctx, &coursepb.CourseImageRequest{
UserId: uint64(req.UserID),
Filename: req.Filename,
MimeType: req.MIMEType,
ImageBytes: req.ImageBytes,
})
return jsonFromResponse(resp, err)
}
func (c *Client) ensureReady() error {
if c == nil || c.rpc == nil {
return errors.New("course zrpc client is not initialized")
}
return nil
}
func (c *Client) ping(timeout time.Duration) error {
if err := c.ensureReady(); err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
_, err := c.rpc.Ping(ctx, &coursepb.StatusResponse{})
return responseFromRPCError(err)
}
func (c *Client) callJSON(ctx context.Context, fn func(context.Context, *coursepb.JSONRequest, ...grpc.CallOption) (*coursepb.JSONResponse, error), payload any) (*coursepb.JSONResponse, error) {
if err := c.ensureReady(); err != nil {
return nil, err
}
raw, err := json.Marshal(payload)
if err != nil {
return nil, err
}
return fn(ctx, &coursepb.JSONRequest{PayloadJson: raw})
}
func jsonFromResponse(resp *coursepb.JSONResponse, rpcErr error) (json.RawMessage, error) {
if rpcErr != nil {
return nil, responseFromRPCError(rpcErr)
}
if resp == nil {
return nil, errors.New("course zrpc service returned empty JSON response")
}
if len(resp.DataJson) == 0 {
return json.RawMessage("null"), nil
}
return json.RawMessage(resp.DataJson), nil
}
func normalizeEndpoints(values []string) []string {
endpoints := make([]string, 0, len(values))
for _, value := range values {
trimmed := strings.TrimSpace(value)
if trimmed != "" {
endpoints = append(endpoints, trimmed)
}
}
return endpoints
}
func normalizeMaxRPCMessageSize(maxImageBytes int64) int {
if maxImageBytes <= 0 {
return defaultMaxRPCMessageSize
}
size := maxImageBytes + rpcMessageSizePadding
if size < defaultMaxRPCMessageSize {
return defaultMaxRPCMessageSize
}
return int(size)
}