Version: 0.9.77.dev.260505
后端:
1.阶段 6 CP4/CP5 目录收口与共享边界纯化
- 将 backend 根目录收口为 services、client、gateway、cmd、shared 五个一级目录
- 收拢 bootstrap、inits、infra/kafka、infra/outbox、conv、respond、pkg、middleware,移除根目录旧实现与空目录
- 将 utils 下沉到 services/userauth/internal/auth,将 logic 下沉到 services/schedule/core/planning
- 将迁移期 runtime 桥接实现统一收拢到 services/runtime/{conv,dao,eventsvc,model},删除 shared/legacy 与未再被 import 的旧 service 实现
- 将 gateway/shared/respond 收口为 HTTP/Gin 错误写回适配,shared/respond 仅保留共享错误语义与状态映射
- 将 HTTP IdempotencyMiddleware 与 RateLimitMiddleware 收口到 gateway/middleware
- 将 GormCachePlugin 下沉到 shared/infra/gormcache,将共享 RateLimiter 下沉到 shared/infra/ratelimit,将 agent token budget 下沉到 services/agent/shared
- 删除 InitEino 兼容壳,收缩 cmd/internal/coreinit 仅保留旧组合壳残留域初始化语义
- 更新微服务迁移计划与桌面 checklist,补齐 CP4/CP5 当前切流点、目录终态与验证结果
- 完成 go test ./...、git diff --check 与最终真实 smoke;health、register/login、task/create+get、schedule/today、task-class/list、memory/items、agent chat/meta/timeline/context-stats 全部 200,SSE 合并结果为 CP5_OK 且 [DONE] 只有 1 个
This commit is contained in:
195
backend/client/activescheduler/client.go
Normal file
195
backend/client/activescheduler/client.go
Normal file
@@ -0,0 +1,195 @@
|
||||
package activescheduler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
activepb "github.com/LoveLosita/smartflow/backend/services/active_scheduler/rpc/pb"
|
||||
contracts "github.com/LoveLosita/smartflow/backend/shared/contracts/activescheduler"
|
||||
"github.com/zeromicro/go-zero/zrpc"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultEndpoint = "127.0.0.1:9083"
|
||||
defaultTimeout = 8 * time.Second
|
||||
)
|
||||
|
||||
type ClientConfig struct {
|
||||
Endpoints []string
|
||||
Target string
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// Client 是 gateway 侧 active-scheduler zrpc 的最小适配层。
|
||||
//
|
||||
// 职责边界:
|
||||
// 1. 只负责跨进程 gRPC 调用和响应 JSON 透传,不碰 DAO、graph、outbox 或 job scanner;
|
||||
// 2. confirm/apply 业务拒绝从 gRPC status 反解成共享 ApplyError,便于 API 层维持既有响应形状;
|
||||
// 3. 复杂响应不在 gateway 重新建模,避免主动调度 DTO 复制扩散。
|
||||
type Client struct {
|
||||
rpc activepb.ActiveSchedulerClient
|
||||
}
|
||||
|
||||
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}
|
||||
}
|
||||
|
||||
zclient, err := zrpc.NewClient(zrpc.RpcClientConf{
|
||||
Endpoints: endpoints,
|
||||
Target: target,
|
||||
NonBlock: true,
|
||||
Timeout: int64(timeout / time.Millisecond),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Client{rpc: activepb.NewActiveSchedulerClient(zclient.Conn())}, nil
|
||||
}
|
||||
|
||||
func (c *Client) DryRun(ctx context.Context, req contracts.ActiveScheduleRequest) (json.RawMessage, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.DryRun(ctx, requestToPB(req))
|
||||
if err != nil {
|
||||
return nil, responseFromRPCError(err)
|
||||
}
|
||||
return jsonFromResponse(resp)
|
||||
}
|
||||
|
||||
func (c *Client) Trigger(ctx context.Context, req contracts.ActiveScheduleRequest) (*contracts.TriggerResponse, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.Trigger(ctx, requestToPB(req))
|
||||
if err != nil {
|
||||
return nil, responseFromRPCError(err)
|
||||
}
|
||||
return triggerFromPB(resp), nil
|
||||
}
|
||||
|
||||
func (c *Client) CreatePreview(ctx context.Context, req contracts.ActiveScheduleRequest) (json.RawMessage, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.CreatePreview(ctx, requestToPB(req))
|
||||
if err != nil {
|
||||
return nil, responseFromRPCError(err)
|
||||
}
|
||||
return jsonFromResponse(resp)
|
||||
}
|
||||
|
||||
func (c *Client) GetPreview(ctx context.Context, req contracts.GetPreviewRequest) (json.RawMessage, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.GetPreview(ctx, &activepb.GetPreviewRequest{
|
||||
UserId: int64(req.UserID),
|
||||
PreviewId: req.PreviewID,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, responseFromRPCError(err)
|
||||
}
|
||||
return jsonFromResponse(resp)
|
||||
}
|
||||
|
||||
func (c *Client) ConfirmPreview(ctx context.Context, req contracts.ConfirmPreviewRequest) (json.RawMessage, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.ConfirmPreview(ctx, confirmToPB(req))
|
||||
if err != nil {
|
||||
return nil, responseFromRPCError(err)
|
||||
}
|
||||
return jsonFromResponse(resp)
|
||||
}
|
||||
|
||||
func (c *Client) ensureReady() error {
|
||||
if c == nil || c.rpc == nil {
|
||||
return errors.New("active-scheduler zrpc client is not initialized")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func requestToPB(req contracts.ActiveScheduleRequest) *activepb.ActiveScheduleRequest {
|
||||
mockNowUnixNano := int64(0)
|
||||
if req.MockNow != nil && !req.MockNow.IsZero() {
|
||||
mockNowUnixNano = req.MockNow.UnixNano()
|
||||
}
|
||||
return &activepb.ActiveScheduleRequest{
|
||||
UserId: int64(req.UserID),
|
||||
TriggerType: req.TriggerType,
|
||||
TargetType: req.TargetType,
|
||||
TargetId: int64(req.TargetID),
|
||||
FeedbackId: req.FeedbackID,
|
||||
IdempotencyKey: req.IdempotencyKey,
|
||||
MockNowUnixNano: mockNowUnixNano,
|
||||
PayloadJson: []byte(req.Payload),
|
||||
}
|
||||
}
|
||||
|
||||
func confirmToPB(req contracts.ConfirmPreviewRequest) *activepb.ConfirmPreviewRequest {
|
||||
requestedAtUnixNano := int64(0)
|
||||
if !req.RequestedAt.IsZero() {
|
||||
requestedAtUnixNano = req.RequestedAt.UnixNano()
|
||||
}
|
||||
return &activepb.ConfirmPreviewRequest{
|
||||
UserId: int64(req.UserID),
|
||||
PreviewId: req.PreviewID,
|
||||
CandidateId: req.CandidateID,
|
||||
Action: req.Action,
|
||||
EditedChangesJson: []byte(req.EditedChanges),
|
||||
IdempotencyKey: req.IdempotencyKey,
|
||||
RequestedAtUnixNano: requestedAtUnixNano,
|
||||
TraceId: req.TraceID,
|
||||
}
|
||||
}
|
||||
|
||||
func triggerFromPB(resp *activepb.TriggerResponse) *contracts.TriggerResponse {
|
||||
if resp == nil {
|
||||
return &contracts.TriggerResponse{}
|
||||
}
|
||||
var previewID *string
|
||||
if resp.HasPreviewId {
|
||||
value := resp.PreviewId
|
||||
previewID = &value
|
||||
}
|
||||
return &contracts.TriggerResponse{
|
||||
TriggerID: resp.TriggerId,
|
||||
Status: resp.Status,
|
||||
PreviewID: previewID,
|
||||
DedupeHit: resp.DedupeHit,
|
||||
TraceID: resp.TraceId,
|
||||
}
|
||||
}
|
||||
|
||||
func jsonFromResponse(resp *activepb.JSONResponse) (json.RawMessage, error) {
|
||||
if resp == nil {
|
||||
return nil, errors.New("active-scheduler 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
|
||||
}
|
||||
116
backend/client/activescheduler/errors.go
Normal file
116
backend/client/activescheduler/errors.go
Normal file
@@ -0,0 +1,116 @@
|
||||
package activescheduler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
contracts "github.com/LoveLosita/smartflow/backend/shared/contracts/activescheduler"
|
||||
"github.com/LoveLosita/smartflow/backend/shared/respond"
|
||||
"google.golang.org/genproto/googleapis/rpc/errdetails"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
const activeSchedulerApplyErrorDomain = "smartflow.active_scheduler.apply"
|
||||
|
||||
// responseFromRPCError 负责把 active-scheduler 的 gRPC 错误反解回项目内错误。
|
||||
//
|
||||
// 职责边界:
|
||||
// 1. confirm/apply 业务错误恢复为 shared/contracts/activescheduler.ApplyError;
|
||||
// 2. 普通业务错误恢复为 respond.Response,供 API 层复用 DealWithError;
|
||||
// 3. 服务不可用或未知内部错误包装成普通 error,避免误报成用户可修正的参数问题。
|
||||
func responseFromRPCError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
st, ok := status.FromError(err)
|
||||
if !ok {
|
||||
return wrapRPCError(err)
|
||||
}
|
||||
if applyErr, ok := applyErrorFromStatus(st); ok {
|
||||
return applyErr
|
||||
}
|
||||
if resp, ok := responseFromStatus(st); ok {
|
||||
return resp
|
||||
}
|
||||
|
||||
switch st.Code() {
|
||||
case codes.Internal, codes.Unknown, codes.Unavailable, codes.DeadlineExceeded, codes.DataLoss, codes.Unimplemented:
|
||||
msg := strings.TrimSpace(st.Message())
|
||||
if msg == "" {
|
||||
msg = "active-scheduler zrpc service internal error"
|
||||
}
|
||||
return wrapRPCError(errors.New(msg))
|
||||
}
|
||||
|
||||
msg := strings.TrimSpace(st.Message())
|
||||
if msg == "" {
|
||||
msg = "active-scheduler zrpc service rejected request"
|
||||
}
|
||||
return respond.Response{Status: grpcCodeToRespondStatus(st.Code()), Info: msg}
|
||||
}
|
||||
|
||||
func applyErrorFromStatus(st *status.Status) (*contracts.ApplyError, bool) {
|
||||
for _, detail := range st.Details() {
|
||||
info, ok := detail.(*errdetails.ErrorInfo)
|
||||
if !ok || info.Domain != activeSchedulerApplyErrorDomain {
|
||||
continue
|
||||
}
|
||||
message := strings.TrimSpace(st.Message())
|
||||
if message == "" && info.Metadata != nil {
|
||||
message = strings.TrimSpace(info.Metadata["info"])
|
||||
}
|
||||
return &contracts.ApplyError{
|
||||
Code: contracts.ApplyErrorCode(strings.TrimSpace(info.Reason)),
|
||||
Message: message,
|
||||
}, true
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
func responseFromStatus(st *status.Status) (respond.Response, bool) {
|
||||
if st == nil {
|
||||
return respond.Response{}, false
|
||||
}
|
||||
for _, detail := range st.Details() {
|
||||
info, ok := detail.(*errdetails.ErrorInfo)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
statusValue := strings.TrimSpace(info.Reason)
|
||||
if statusValue == "" {
|
||||
statusValue = grpcCodeToRespondStatus(st.Code())
|
||||
}
|
||||
message := strings.TrimSpace(st.Message())
|
||||
if message == "" && info.Metadata != nil {
|
||||
message = strings.TrimSpace(info.Metadata["info"])
|
||||
}
|
||||
if message == "" {
|
||||
message = statusValue
|
||||
}
|
||||
return respond.Response{Status: statusValue, Info: message}, true
|
||||
}
|
||||
return respond.Response{}, false
|
||||
}
|
||||
|
||||
func grpcCodeToRespondStatus(code codes.Code) string {
|
||||
switch code {
|
||||
case codes.Unauthenticated:
|
||||
return respond.ErrUnauthorized.Status
|
||||
case codes.InvalidArgument:
|
||||
return respond.MissingParam.Status
|
||||
case codes.Internal, codes.Unknown, codes.DataLoss:
|
||||
return "500"
|
||||
default:
|
||||
return "400"
|
||||
}
|
||||
}
|
||||
|
||||
func wrapRPCError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("调用 active-scheduler zrpc 服务失败: %w", err)
|
||||
}
|
||||
Reference in New Issue
Block a user