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)
|
||||
}
|
||||
192
backend/client/agent/client.go
Normal file
192
backend/client/agent/client.go
Normal file
@@ -0,0 +1,192 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
agentpb "github.com/LoveLosita/smartflow/backend/services/agent/rpc/pb"
|
||||
agentcontracts "github.com/LoveLosita/smartflow/backend/shared/contracts/agent"
|
||||
"github.com/zeromicro/go-zero/zrpc"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultEndpoint = "127.0.0.1:9089"
|
||||
defaultTimeout = 0
|
||||
)
|
||||
|
||||
type ClientConfig struct {
|
||||
Endpoints []string
|
||||
Target string
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// Client 是 gateway 访问 agent zrpc 的流式适配层。
|
||||
//
|
||||
// 职责边界:
|
||||
// 1. 只负责跨进程 gRPC stream 调用,不感知 Gin / SSE;
|
||||
// 2. ChatChunk 的 payload 保持 agent 服务原样输出,Gateway API 再转成 SSE data;
|
||||
// 3. agent.rpc.chat.enabled 关闭时,调用方仍可走本地 AgentService 回退链路。
|
||||
type Client struct {
|
||||
rpc agentpb.AgentClient
|
||||
}
|
||||
|
||||
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: agentpb.NewAgentClient(zclient.Conn())}, nil
|
||||
}
|
||||
|
||||
func (c *Client) Ping(ctx context.Context) error {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := c.rpc.Ping(ctx, &agentpb.StatusResponse{})
|
||||
return responseFromRPCError(err)
|
||||
}
|
||||
|
||||
func (c *Client) Chat(ctx context.Context, req agentcontracts.ChatRequest) (*ChatStream, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
stream, err := c.rpc.Chat(ctx, &agentpb.ChatRequest{
|
||||
Message: req.Message,
|
||||
Thinking: req.Thinking,
|
||||
Model: req.Model,
|
||||
UserId: int32(req.UserID),
|
||||
ConversationId: req.ConversationID,
|
||||
ExtraJson: append([]byte(nil), req.ExtraJSON...),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, responseFromRPCError(err)
|
||||
}
|
||||
return &ChatStream{stream: stream}, nil
|
||||
}
|
||||
|
||||
func (c *Client) GetConversationMeta(ctx context.Context, req agentcontracts.ConversationQueryRequest) (json.RawMessage, error) {
|
||||
resp, err := c.callJSON(ctx, c.rpc.GetConversationMeta, req)
|
||||
return jsonFromResponse(resp, err)
|
||||
}
|
||||
|
||||
func (c *Client) GetConversationList(ctx context.Context, req agentcontracts.ConversationListRequest) (json.RawMessage, error) {
|
||||
resp, err := c.callJSON(ctx, c.rpc.GetConversationList, req)
|
||||
return jsonFromResponse(resp, err)
|
||||
}
|
||||
|
||||
func (c *Client) GetConversationTimeline(ctx context.Context, req agentcontracts.ConversationQueryRequest) (json.RawMessage, error) {
|
||||
resp, err := c.callJSON(ctx, c.rpc.GetConversationTimeline, req)
|
||||
return jsonFromResponse(resp, err)
|
||||
}
|
||||
|
||||
func (c *Client) GetSchedulePlanPreview(ctx context.Context, req agentcontracts.ConversationQueryRequest) (json.RawMessage, error) {
|
||||
resp, err := c.callJSON(ctx, c.rpc.GetSchedulePlanPreview, req)
|
||||
return jsonFromResponse(resp, err)
|
||||
}
|
||||
|
||||
func (c *Client) GetContextStats(ctx context.Context, req agentcontracts.ConversationQueryRequest) (string, error) {
|
||||
resp, err := c.callJSON(ctx, c.rpc.GetContextStats, req)
|
||||
raw, err := jsonFromResponse(resp, err)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(raw), nil
|
||||
}
|
||||
|
||||
func (c *Client) SaveScheduleState(ctx context.Context, req agentcontracts.SaveScheduleStateRequest) error {
|
||||
_, err := c.callJSON(ctx, c.rpc.SaveScheduleState, req)
|
||||
return responseFromRPCError(err)
|
||||
}
|
||||
|
||||
type ChatStream struct {
|
||||
stream agentpb.Agent_ChatClient
|
||||
}
|
||||
|
||||
// Recv 读取 agent RPC 的下一段输出。
|
||||
//
|
||||
// 返回语义:
|
||||
// 1. io.EOF 表示服务端正常关闭 stream;
|
||||
// 2. 其它 error 已尽量反解为项目内错误;
|
||||
// 3. chunk.Done 由上层决定是否写出 [DONE]。
|
||||
func (s *ChatStream) Recv() (agentcontracts.ChatChunk, error) {
|
||||
if s == nil || s.stream == nil {
|
||||
return agentcontracts.ChatChunk{}, errors.New("agent zrpc stream is not initialized")
|
||||
}
|
||||
chunk, err := s.stream.Recv()
|
||||
if err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
return agentcontracts.ChatChunk{}, io.EOF
|
||||
}
|
||||
return agentcontracts.ChatChunk{}, responseFromRPCError(err)
|
||||
}
|
||||
if chunk == nil {
|
||||
return agentcontracts.ChatChunk{}, errors.New("agent zrpc service returned empty chunk")
|
||||
}
|
||||
return agentcontracts.ChatChunk{
|
||||
Payload: chunk.Payload,
|
||||
Done: chunk.Done,
|
||||
ErrorJSON: append([]byte(nil), chunk.ErrorJson...),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *Client) ensureReady() error {
|
||||
if c == nil || c.rpc == nil {
|
||||
return errors.New("agent zrpc client is not initialized")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) callJSON(ctx context.Context, fn func(context.Context, *agentpb.JSONRequest, ...grpc.CallOption) (*agentpb.JSONResponse, error), payload any) (*agentpb.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, &agentpb.JSONRequest{PayloadJson: raw})
|
||||
}
|
||||
|
||||
func jsonFromResponse(resp *agentpb.JSONResponse, rpcErr error) (json.RawMessage, error) {
|
||||
if rpcErr != nil {
|
||||
return nil, responseFromRPCError(rpcErr)
|
||||
}
|
||||
if resp == nil {
|
||||
return nil, errors.New("agent 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
|
||||
}
|
||||
94
backend/client/agent/errors.go
Normal file
94
backend/client/agent/errors.go
Normal file
@@ -0,0 +1,94 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/LoveLosita/smartflow/backend/shared/respond"
|
||||
"google.golang.org/genproto/googleapis/rpc/errdetails"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// responseFromRPCError 负责把 agent 的 gRPC 错误反解回项目内错误。
|
||||
//
|
||||
// 职责边界:
|
||||
// 1. 只在 gateway 边缘层使用;
|
||||
// 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 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 = "agent zrpc service internal error"
|
||||
}
|
||||
return wrapRPCError(errors.New(msg))
|
||||
}
|
||||
|
||||
msg := strings.TrimSpace(st.Message())
|
||||
if msg == "" {
|
||||
msg = "agent zrpc service rejected request"
|
||||
}
|
||||
return respond.Response{Status: grpcCodeToRespondStatus(st.Code()), Info: msg}
|
||||
}
|
||||
|
||||
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.NotFound:
|
||||
return respond.ConversationNotFound.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("调用 agent zrpc 服务失败: %w", err)
|
||||
}
|
||||
162
backend/client/course/client.go
Normal file
162
backend/client/course/client.go
Normal file
@@ -0,0 +1,162 @@
|
||||
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"
|
||||
defaultTimeout = 10 * time.Second
|
||||
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{
|
||||
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)
|
||||
}
|
||||
111
backend/client/course/errors.go
Normal file
111
backend/client/course/errors.go
Normal file
@@ -0,0 +1,111 @@
|
||||
package course
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/LoveLosita/smartflow/backend/shared/respond"
|
||||
"google.golang.org/genproto/googleapis/rpc/errdetails"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// CourseImportConflictError 表示课程导入和已有非课程日程冲突。
|
||||
//
|
||||
// 职责边界:
|
||||
// 1. 只在 gateway 边缘层用于恢复旧 HTTP 409 + conflicts 响应;
|
||||
// 2. 不承载冲突计算逻辑,冲突详情由 course 服务生成;
|
||||
// 3. ConflictsJSON 返回原始 JSON,避免 gateway 复制 schedule 冲突 DTO。
|
||||
type CourseImportConflictError struct {
|
||||
conflicts json.RawMessage
|
||||
}
|
||||
|
||||
func (e CourseImportConflictError) Error() string {
|
||||
return respond.ScheduleConflict.Info
|
||||
}
|
||||
|
||||
func (e CourseImportConflictError) ConflictsJSON() json.RawMessage {
|
||||
if len(e.conflicts) == 0 {
|
||||
return json.RawMessage("[]")
|
||||
}
|
||||
return e.conflicts
|
||||
}
|
||||
|
||||
// responseFromRPCError 负责把 course 的 gRPC 错误反解回项目内错误。
|
||||
func responseFromRPCError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
st, ok := status.FromError(err)
|
||||
if !ok {
|
||||
return wrapRPCError(err)
|
||||
}
|
||||
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 = "course zrpc service internal error"
|
||||
}
|
||||
return wrapRPCError(errors.New(msg))
|
||||
}
|
||||
|
||||
msg := strings.TrimSpace(st.Message())
|
||||
if msg == "" {
|
||||
msg = "course zrpc service rejected request"
|
||||
}
|
||||
return respond.Response{Status: grpcCodeToRespondStatus(st.Code()), Info: msg}
|
||||
}
|
||||
|
||||
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.PermissionDenied:
|
||||
return respond.ErrUnauthorized.Status
|
||||
case codes.InvalidArgument:
|
||||
return respond.WrongParamType.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("调用 course zrpc 服务失败: %w", err)
|
||||
}
|
||||
155
backend/client/memory/client.go
Normal file
155
backend/client/memory/client.go
Normal file
@@ -0,0 +1,155 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
memorypb "github.com/LoveLosita/smartflow/backend/services/memory/rpc/pb"
|
||||
memorycontracts "github.com/LoveLosita/smartflow/backend/shared/contracts/memory"
|
||||
"github.com/zeromicro/go-zero/zrpc"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultEndpoint = "127.0.0.1:9088"
|
||||
defaultTimeout = 6 * time.Second
|
||||
)
|
||||
|
||||
type ClientConfig struct {
|
||||
Endpoints []string
|
||||
Target string
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// Client 是 gateway 访问 memory zrpc 的最小适配层。
|
||||
//
|
||||
// 职责边界:
|
||||
// 1. 只负责跨进程 gRPC 调用和 JSON 透传,不触碰 memory repo、worker 或 outbox;
|
||||
// 2. HTTP 入参仍由 gateway/api 做基础绑定,业务校验交给 memory 服务;
|
||||
// 3. 复杂响应不在 gateway 重建模型,避免 DTO 复制扩散。
|
||||
type Client struct {
|
||||
rpc memorypb.MemoryClient
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
// 1. 这里不在构造期 Ping memory 服务,避免 cmd/memory 短暂不可用时拖垮整个 gateway/worker 启动。
|
||||
// 2. 真正的可用性检查延迟到各个 RPC 调用,由 `/api/v1/memory/*` 自己返回局部错误。
|
||||
client := &Client{rpc: memorypb.NewMemoryClient(zclient.Conn())}
|
||||
return client, nil
|
||||
}
|
||||
|
||||
// Retrieve 调用 memory 服务完成 agent 记忆读取。
|
||||
//
|
||||
// 职责边界:
|
||||
// 1. 只负责跨进程 JSON 编解码和 gRPC 错误还原;
|
||||
// 2. 不在 gateway 侧重做召回、过滤或 prompt 渲染;
|
||||
// 3. 返回 ItemDTO 给 agent 适配器继续转换为内部模型。
|
||||
func (c *Client) Retrieve(ctx context.Context, req memorycontracts.RetrieveRequest) ([]memorycontracts.ItemDTO, error) {
|
||||
resp, err := c.callJSON(ctx, c.rpc.Retrieve, req)
|
||||
raw, err := jsonFromResponse(resp, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(raw) == 0 || string(raw) == "null" {
|
||||
return nil, nil
|
||||
}
|
||||
var items []memorycontracts.ItemDTO
|
||||
if err := json.Unmarshal(raw, &items); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func (c *Client) ListItems(ctx context.Context, req memorycontracts.ListItemsRequest) (json.RawMessage, error) {
|
||||
resp, err := c.callJSON(ctx, c.rpc.ListItems, req)
|
||||
return jsonFromResponse(resp, err)
|
||||
}
|
||||
|
||||
func (c *Client) GetItem(ctx context.Context, req memorycontracts.GetItemRequest) (json.RawMessage, error) {
|
||||
resp, err := c.callJSON(ctx, c.rpc.GetItem, req)
|
||||
return jsonFromResponse(resp, err)
|
||||
}
|
||||
|
||||
func (c *Client) CreateItem(ctx context.Context, req memorycontracts.CreateItemRequest) (json.RawMessage, error) {
|
||||
resp, err := c.callJSON(ctx, c.rpc.CreateItem, req)
|
||||
return jsonFromResponse(resp, err)
|
||||
}
|
||||
|
||||
func (c *Client) UpdateItem(ctx context.Context, req memorycontracts.UpdateItemRequest) (json.RawMessage, error) {
|
||||
resp, err := c.callJSON(ctx, c.rpc.UpdateItem, req)
|
||||
return jsonFromResponse(resp, err)
|
||||
}
|
||||
|
||||
func (c *Client) DeleteItem(ctx context.Context, req memorycontracts.DeleteItemRequest) (json.RawMessage, error) {
|
||||
resp, err := c.callJSON(ctx, c.rpc.DeleteItem, req)
|
||||
return jsonFromResponse(resp, err)
|
||||
}
|
||||
|
||||
func (c *Client) RestoreItem(ctx context.Context, req memorycontracts.RestoreItemRequest) (json.RawMessage, error) {
|
||||
resp, err := c.callJSON(ctx, c.rpc.RestoreItem, req)
|
||||
return jsonFromResponse(resp, err)
|
||||
}
|
||||
|
||||
func (c *Client) ensureReady() error {
|
||||
if c == nil || c.rpc == nil {
|
||||
return errors.New("memory zrpc client is not initialized")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) callJSON(ctx context.Context, fn func(context.Context, *memorypb.JSONRequest, ...grpc.CallOption) (*memorypb.JSONResponse, error), payload any) (*memorypb.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, &memorypb.JSONRequest{PayloadJson: raw})
|
||||
}
|
||||
|
||||
func jsonFromResponse(resp *memorypb.JSONResponse, rpcErr error) (json.RawMessage, error) {
|
||||
if rpcErr != nil {
|
||||
return nil, responseFromRPCError(rpcErr)
|
||||
}
|
||||
if resp == nil {
|
||||
return nil, errors.New("memory 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
|
||||
}
|
||||
94
backend/client/memory/errors.go
Normal file
94
backend/client/memory/errors.go
Normal file
@@ -0,0 +1,94 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/LoveLosita/smartflow/backend/shared/respond"
|
||||
"google.golang.org/genproto/googleapis/rpc/errdetails"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// responseFromRPCError 负责把 memory 的 gRPC 错误反解回项目内错误。
|
||||
//
|
||||
// 职责边界:
|
||||
// 1. 只在 gateway 边缘层使用;
|
||||
// 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 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 = "memory zrpc service internal error"
|
||||
}
|
||||
return wrapRPCError(errors.New(msg))
|
||||
}
|
||||
|
||||
msg := strings.TrimSpace(st.Message())
|
||||
if msg == "" {
|
||||
msg = "memory zrpc service rejected request"
|
||||
}
|
||||
return respond.Response{Status: grpcCodeToRespondStatus(st.Code()), Info: msg}
|
||||
}
|
||||
|
||||
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.NotFound:
|
||||
return respond.MemoryItemNotFound.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("调用 memory zrpc 服务失败: %w", err)
|
||||
}
|
||||
181
backend/client/notification/client.go
Normal file
181
backend/client/notification/client.go
Normal file
@@ -0,0 +1,181 @@
|
||||
package notification
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
notificationpb "github.com/LoveLosita/smartflow/backend/services/notification/rpc/pb"
|
||||
contracts "github.com/LoveLosita/smartflow/backend/shared/contracts/notification"
|
||||
"github.com/zeromicro/go-zero/zrpc"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultEndpoint = "127.0.0.1:9082"
|
||||
defaultTimeout = 6 * time.Second
|
||||
)
|
||||
|
||||
type ClientConfig struct {
|
||||
Endpoints []string
|
||||
Target string
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// Client 是 gateway 侧 notification zrpc 的最小适配层。
|
||||
//
|
||||
// 职责边界:
|
||||
// 1. 只负责跨进程 gRPC 调用和响应转译,不碰 DB / provider / outbox 细节;
|
||||
// 2. 服务端业务错误先通过 gRPC status 传输,再在这里反解回 respond.Response 风格;
|
||||
// 3. 上层调用方仍然可以保持 `res, err :=` 的统一用法。
|
||||
type Client struct {
|
||||
rpc notificationpb.NotificationClient
|
||||
}
|
||||
|
||||
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: notificationpb.NewNotificationClient(zclient.Conn())}, nil
|
||||
}
|
||||
|
||||
func (c *Client) GetFeishuWebhook(ctx context.Context, req contracts.GetFeishuWebhookRequest) (*contracts.ChannelResponse, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.GetFeishuWebhook(ctx, ¬ificationpb.GetFeishuWebhookRequest{
|
||||
UserId: int64(req.UserID),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, responseFromRPCError(err)
|
||||
}
|
||||
return channelFromResponse(resp)
|
||||
}
|
||||
|
||||
func (c *Client) SaveFeishuWebhook(ctx context.Context, req contracts.SaveFeishuWebhookRequest) (*contracts.ChannelResponse, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.SaveFeishuWebhook(ctx, ¬ificationpb.SaveFeishuWebhookRequest{
|
||||
UserId: int64(req.UserID),
|
||||
Enabled: req.Enabled,
|
||||
WebhookUrl: req.WebhookURL,
|
||||
AuthType: req.AuthType,
|
||||
BearerToken: req.BearerToken,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, responseFromRPCError(err)
|
||||
}
|
||||
return channelFromResponse(resp)
|
||||
}
|
||||
|
||||
func (c *Client) DeleteFeishuWebhook(ctx context.Context, req contracts.DeleteFeishuWebhookRequest) error {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := c.rpc.DeleteFeishuWebhook(ctx, ¬ificationpb.DeleteFeishuWebhookRequest{
|
||||
UserId: int64(req.UserID),
|
||||
})
|
||||
if err != nil {
|
||||
return responseFromRPCError(err)
|
||||
}
|
||||
if resp == nil {
|
||||
return errors.New("notification zrpc service returned empty delete response")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) TestFeishuWebhook(ctx context.Context, req contracts.TestFeishuWebhookRequest) (*contracts.TestResult, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.TestFeishuWebhook(ctx, ¬ificationpb.TestFeishuWebhookRequest{
|
||||
UserId: int64(req.UserID),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, responseFromRPCError(err)
|
||||
}
|
||||
return testResultFromResponse(resp)
|
||||
}
|
||||
|
||||
func (c *Client) ensureReady() error {
|
||||
if c == nil || c.rpc == nil {
|
||||
return errors.New("notification zrpc client is not initialized")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func channelFromResponse(resp *notificationpb.ChannelResponse) (*contracts.ChannelResponse, error) {
|
||||
if resp == nil {
|
||||
return nil, errors.New("notification zrpc service returned empty channel response")
|
||||
}
|
||||
var lastTestAt *time.Time
|
||||
if value := timeFromUnixNano(resp.LastTestAtUnixNano); !value.IsZero() {
|
||||
lastTestAt = &value
|
||||
}
|
||||
return &contracts.ChannelResponse{
|
||||
Channel: resp.Channel,
|
||||
Enabled: resp.Enabled,
|
||||
Configured: resp.Configured,
|
||||
WebhookURLMask: resp.WebhookUrlMask,
|
||||
AuthType: resp.AuthType,
|
||||
HasBearerToken: resp.HasBearerToken,
|
||||
LastTestStatus: resp.LastTestStatus,
|
||||
LastTestError: resp.LastTestError,
|
||||
LastTestAt: lastTestAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func testResultFromResponse(resp *notificationpb.TestResult) (*contracts.TestResult, error) {
|
||||
if resp == nil {
|
||||
return nil, errors.New("notification zrpc service returned empty test response")
|
||||
}
|
||||
channel, err := channelFromResponse(resp.Channel)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &contracts.TestResult{
|
||||
Channel: *channel,
|
||||
Status: resp.Status,
|
||||
Outcome: resp.Outcome,
|
||||
Message: resp.Message,
|
||||
TraceID: resp.TraceId,
|
||||
SentAt: timeFromUnixNano(resp.SentAtUnixNano),
|
||||
Skipped: resp.Skipped,
|
||||
Provider: resp.Provider,
|
||||
}, 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 timeFromUnixNano(value int64) time.Time {
|
||||
if value <= 0 {
|
||||
return time.Time{}
|
||||
}
|
||||
return time.Unix(0, value)
|
||||
}
|
||||
151
backend/client/notification/errors.go
Normal file
151
backend/client/notification/errors.go
Normal file
@@ -0,0 +1,151 @@
|
||||
package notification
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/LoveLosita/smartflow/backend/shared/respond"
|
||||
"google.golang.org/genproto/googleapis/rpc/errdetails"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// responseFromRPCError 负责把 notification 的 gRPC 错误反解回项目内的 respond.Response。
|
||||
//
|
||||
// 职责边界:
|
||||
// 1. 只在 gateway 边缘层使用,不下沉到服务实现里;
|
||||
// 2. 业务错误尽量恢复成 respond.Response,方便 API 层继续复用现有 DealWithError;
|
||||
// 3. 只要拿不到业务语义,就退化成普通 error,让上层按 500 处理。
|
||||
func responseFromRPCError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
st, ok := status.FromError(err)
|
||||
if !ok {
|
||||
return wrapRPCError(err)
|
||||
}
|
||||
|
||||
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 = "notification zrpc service internal error"
|
||||
}
|
||||
return wrapRPCError(errors.New(msg))
|
||||
}
|
||||
|
||||
msg := strings.TrimSpace(st.Message())
|
||||
if msg == "" {
|
||||
msg = "notification zrpc service rejected request"
|
||||
}
|
||||
return respond.Response{
|
||||
Status: grpcCodeToRespondStatus(st.Code()),
|
||||
Info: msg,
|
||||
}
|
||||
}
|
||||
|
||||
func responseFromStatus(st *status.Status) (respond.Response, bool) {
|
||||
if st == nil {
|
||||
return respond.Response{}, false
|
||||
}
|
||||
|
||||
if resp, ok := responseFromStatusDetails(st); ok {
|
||||
return resp, true
|
||||
}
|
||||
if resp, ok := responseFromLegacyStatus(st.Code(), st.Message()); ok {
|
||||
return resp, true
|
||||
}
|
||||
return respond.Response{}, false
|
||||
}
|
||||
|
||||
func responseFromStatusDetails(st *status.Status) (respond.Response, bool) {
|
||||
for _, detail := range st.Details() {
|
||||
info, ok := detail.(*errdetails.ErrorInfo)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
statusValue := strings.TrimSpace(info.Reason)
|
||||
if statusValue == "" {
|
||||
statusValue = grpcCodeToRespondStatus(st.Code())
|
||||
}
|
||||
if statusValue == "" {
|
||||
return respond.Response{}, false
|
||||
}
|
||||
|
||||
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 responseFromLegacyStatus(code codes.Code, message string) (respond.Response, bool) {
|
||||
trimmed := strings.TrimSpace(message)
|
||||
if resp, ok := respondResponseByMessage(trimmed); ok {
|
||||
return resp, true
|
||||
}
|
||||
|
||||
switch code {
|
||||
case codes.Unauthenticated:
|
||||
if trimmed == "" {
|
||||
trimmed = "unauthorized"
|
||||
}
|
||||
return respond.Response{Status: respond.ErrUnauthorized.Status, Info: trimmed}, true
|
||||
case codes.InvalidArgument:
|
||||
if trimmed == "" {
|
||||
trimmed = "invalid argument"
|
||||
}
|
||||
return respond.Response{Status: respond.MissingParam.Status, Info: trimmed}, true
|
||||
case codes.Internal, codes.Unknown, codes.DataLoss:
|
||||
if trimmed == "" {
|
||||
trimmed = "notification service internal error"
|
||||
}
|
||||
return respond.InternalError(errors.New(trimmed)), true
|
||||
}
|
||||
|
||||
return respond.Response{}, false
|
||||
}
|
||||
|
||||
func respondResponseByMessage(message string) (respond.Response, bool) {
|
||||
switch strings.TrimSpace(message) {
|
||||
case respond.MissingParam.Info:
|
||||
return respond.MissingParam, true
|
||||
case respond.WrongParamType.Info:
|
||||
return respond.WrongParamType, true
|
||||
case respond.ErrUnauthorized.Info:
|
||||
return respond.ErrUnauthorized, 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("调用 notification zrpc 服务失败: %w", err)
|
||||
}
|
||||
202
backend/client/schedule/client.go
Normal file
202
backend/client/schedule/client.go
Normal file
@@ -0,0 +1,202 @@
|
||||
package schedule
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
schedulepb "github.com/LoveLosita/smartflow/backend/services/schedule/rpc/pb"
|
||||
schedulecontracts "github.com/LoveLosita/smartflow/backend/shared/contracts/schedule"
|
||||
"github.com/zeromicro/go-zero/zrpc"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultEndpoint = "127.0.0.1:9084"
|
||||
defaultTimeout = 6 * time.Second
|
||||
)
|
||||
|
||||
type ClientConfig struct {
|
||||
Endpoints []string
|
||||
Target string
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// Client 是 gateway 侧 schedule zrpc 的最小适配层。
|
||||
//
|
||||
// 职责边界:
|
||||
// 1. 只负责跨进程 gRPC 调用和 JSON 透传,不碰 DAO、粗排算法或正式日程 apply 状态机;
|
||||
// 2. HTTP 入参仍由 gateway/api 做基础绑定,业务校验交给 schedule 服务;
|
||||
// 3. 复杂响应不在 gateway 重建模型,避免 DTO 复制扩散。
|
||||
type Client struct {
|
||||
rpc schedulepb.ScheduleClient
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
client := &Client{rpc: schedulepb.NewScheduleClient(zclient.Conn())}
|
||||
if err := client.ping(timeout); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func (c *Client) GetUserTodaySchedule(ctx context.Context, userID int) (json.RawMessage, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.GetToday(ctx, &schedulepb.UserRequest{UserId: int64(userID)})
|
||||
return jsonFromResponse(resp, err)
|
||||
}
|
||||
|
||||
func (c *Client) GetUserWeeklySchedule(ctx context.Context, userID int, week int) (json.RawMessage, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.GetWeek(ctx, &schedulepb.WeekRequest{UserId: int64(userID), Week: int64(week)})
|
||||
return jsonFromResponse(resp, err)
|
||||
}
|
||||
|
||||
func (c *Client) DeleteScheduleEvent(ctx context.Context, req schedulecontracts.DeleteScheduleEventsRequest) error {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return err
|
||||
}
|
||||
eventsJSON, err := json.Marshal(req.Events)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = c.rpc.DeleteEvents(ctx, &schedulepb.DeleteEventsRequest{
|
||||
UserId: int64(req.UserID),
|
||||
EventsJson: eventsJSON,
|
||||
})
|
||||
return responseFromRPCError(err)
|
||||
}
|
||||
|
||||
func (c *Client) GetUserRecentCompletedSchedules(ctx context.Context, req schedulecontracts.RecentCompletedRequest) (json.RawMessage, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.GetRecentCompleted(ctx, &schedulepb.RecentCompletedRequest{
|
||||
UserId: int64(req.UserID),
|
||||
Index: int64(req.Index),
|
||||
Limit: int64(req.Limit),
|
||||
})
|
||||
return jsonFromResponse(resp, err)
|
||||
}
|
||||
|
||||
func (c *Client) GetUserOngoingSchedule(ctx context.Context, userID int) (json.RawMessage, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.GetCurrent(ctx, &schedulepb.UserRequest{UserId: int64(userID)})
|
||||
return jsonFromResponse(resp, err)
|
||||
}
|
||||
|
||||
func (c *Client) RevokeTaskItemFromSchedule(ctx context.Context, req schedulecontracts.RevokeTaskItemRequest) error {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := c.rpc.RevokeTaskItem(ctx, &schedulepb.RevokeTaskItemRequest{
|
||||
UserId: int64(req.UserID),
|
||||
EventId: int64(req.EventID),
|
||||
})
|
||||
return responseFromRPCError(err)
|
||||
}
|
||||
|
||||
func (c *Client) SmartPlanning(ctx context.Context, req schedulecontracts.SmartPlanningRequest) (json.RawMessage, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.SmartPlanning(ctx, &schedulepb.SmartPlanningRequest{
|
||||
UserId: int64(req.UserID),
|
||||
TaskClassId: int64(req.TaskClassID),
|
||||
})
|
||||
return jsonFromResponse(resp, err)
|
||||
}
|
||||
|
||||
func (c *Client) SmartPlanningMulti(ctx context.Context, req schedulecontracts.SmartPlanningMultiRequest) (json.RawMessage, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
taskClassIDs := make([]int64, 0, len(req.TaskClassIDs))
|
||||
for _, id := range req.TaskClassIDs {
|
||||
taskClassIDs = append(taskClassIDs, int64(id))
|
||||
}
|
||||
resp, err := c.rpc.SmartPlanningMulti(ctx, &schedulepb.SmartPlanningMultiRequest{
|
||||
UserId: int64(req.UserID),
|
||||
TaskClassIds: taskClassIDs,
|
||||
})
|
||||
return jsonFromResponse(resp, err)
|
||||
}
|
||||
|
||||
func (c *Client) GetAgentWeekSchedule(ctx context.Context, req schedulecontracts.AgentScheduleWeekRequest) (json.RawMessage, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
payload, err := json.Marshal(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.GetAgentWeekSchedule(ctx, &schedulepb.JSONRequest{PayloadJson: payload})
|
||||
return jsonFromResponse(resp, err)
|
||||
}
|
||||
|
||||
func (c *Client) ensureReady() error {
|
||||
if c == nil || c.rpc == nil {
|
||||
return errors.New("schedule 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, &schedulepb.StatusResponse{})
|
||||
return responseFromRPCError(err)
|
||||
}
|
||||
|
||||
func jsonFromResponse(resp *schedulepb.JSONResponse, rpcErr error) (json.RawMessage, error) {
|
||||
if rpcErr != nil {
|
||||
return nil, responseFromRPCError(rpcErr)
|
||||
}
|
||||
if resp == nil {
|
||||
return nil, errors.New("schedule 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
|
||||
}
|
||||
92
backend/client/schedule/errors.go
Normal file
92
backend/client/schedule/errors.go
Normal file
@@ -0,0 +1,92 @@
|
||||
package schedule
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/LoveLosita/smartflow/backend/shared/respond"
|
||||
"google.golang.org/genproto/googleapis/rpc/errdetails"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// responseFromRPCError 负责把 schedule 的 gRPC 错误反解回项目内错误。
|
||||
//
|
||||
// 职责边界:
|
||||
// 1. 只在 gateway 边缘层使用,不下沉到 schedule 服务实现里;
|
||||
// 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 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 = "schedule zrpc service internal error"
|
||||
}
|
||||
return wrapRPCError(errors.New(msg))
|
||||
}
|
||||
|
||||
msg := strings.TrimSpace(st.Message())
|
||||
if msg == "" {
|
||||
msg = "schedule zrpc service rejected request"
|
||||
}
|
||||
return respond.Response{Status: grpcCodeToRespondStatus(st.Code()), Info: msg}
|
||||
}
|
||||
|
||||
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("调用 schedule zrpc 服务失败: %w", err)
|
||||
}
|
||||
149
backend/client/task/client.go
Normal file
149
backend/client/task/client.go
Normal file
@@ -0,0 +1,149 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
taskpb "github.com/LoveLosita/smartflow/backend/services/task/rpc/pb"
|
||||
taskcontracts "github.com/LoveLosita/smartflow/backend/shared/contracts/task"
|
||||
"github.com/zeromicro/go-zero/zrpc"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultEndpoint = "127.0.0.1:9085"
|
||||
defaultTimeout = 6 * time.Second
|
||||
)
|
||||
|
||||
type ClientConfig struct {
|
||||
Endpoints []string
|
||||
Target string
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// Client 是 gateway 侧 task zrpc 的最小适配层。
|
||||
//
|
||||
// 职责边界:
|
||||
// 1. 只负责跨进程 gRPC 调用和 JSON 透传,不碰 DAO、outbox 或 active-scheduler job;
|
||||
// 2. HTTP 入参仍由 gateway/api 做基础绑定,业务校验交给 task 服务;
|
||||
// 3. 复杂响应不在 gateway 重建模型,避免 DTO 复制扩散。
|
||||
type Client struct {
|
||||
rpc taskpb.TaskClient
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
client := &Client{rpc: taskpb.NewTaskClient(zclient.Conn())}
|
||||
if err := client.ping(timeout); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func (c *Client) AddTask(ctx context.Context, req taskcontracts.AddTaskRequest) (json.RawMessage, error) {
|
||||
resp, err := c.callJSON(ctx, c.rpc.AddTask, req)
|
||||
return jsonFromResponse(resp, err)
|
||||
}
|
||||
|
||||
func (c *Client) GetUserTasks(ctx context.Context, userID int) (json.RawMessage, error) {
|
||||
resp, err := c.callJSON(ctx, c.rpc.GetUserTasks, taskcontracts.UserRequest{UserID: userID})
|
||||
return jsonFromResponse(resp, err)
|
||||
}
|
||||
|
||||
func (c *Client) BatchTaskStatus(ctx context.Context, req taskcontracts.BatchTaskStatusRequest) (json.RawMessage, error) {
|
||||
resp, err := c.callJSON(ctx, c.rpc.BatchTaskStatus, req)
|
||||
return jsonFromResponse(resp, err)
|
||||
}
|
||||
|
||||
func (c *Client) CompleteTask(ctx context.Context, req taskcontracts.CompleteTaskRequest) (json.RawMessage, error) {
|
||||
resp, err := c.callJSON(ctx, c.rpc.CompleteTask, req)
|
||||
return jsonFromResponse(resp, err)
|
||||
}
|
||||
|
||||
func (c *Client) UndoCompleteTask(ctx context.Context, req taskcontracts.UndoCompleteTaskRequest) (json.RawMessage, error) {
|
||||
resp, err := c.callJSON(ctx, c.rpc.UndoCompleteTask, req)
|
||||
return jsonFromResponse(resp, err)
|
||||
}
|
||||
|
||||
func (c *Client) UpdateTask(ctx context.Context, req taskcontracts.UpdateTaskRequest) (json.RawMessage, error) {
|
||||
resp, err := c.callJSON(ctx, c.rpc.UpdateTask, req)
|
||||
return jsonFromResponse(resp, err)
|
||||
}
|
||||
|
||||
func (c *Client) DeleteTask(ctx context.Context, req taskcontracts.DeleteTaskRequest) (json.RawMessage, error) {
|
||||
resp, err := c.callJSON(ctx, c.rpc.DeleteTask, req)
|
||||
return jsonFromResponse(resp, err)
|
||||
}
|
||||
|
||||
func (c *Client) ensureReady() error {
|
||||
if c == nil || c.rpc == nil {
|
||||
return errors.New("task 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, &taskpb.StatusResponse{})
|
||||
return responseFromRPCError(err)
|
||||
}
|
||||
|
||||
func (c *Client) callJSON(ctx context.Context, fn func(context.Context, *taskpb.JSONRequest, ...grpc.CallOption) (*taskpb.JSONResponse, error), payload any) (*taskpb.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, &taskpb.JSONRequest{PayloadJson: raw})
|
||||
}
|
||||
|
||||
func jsonFromResponse(resp *taskpb.JSONResponse, rpcErr error) (json.RawMessage, error) {
|
||||
if rpcErr != nil {
|
||||
return nil, responseFromRPCError(rpcErr)
|
||||
}
|
||||
if resp == nil {
|
||||
return nil, errors.New("task 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
|
||||
}
|
||||
94
backend/client/task/errors.go
Normal file
94
backend/client/task/errors.go
Normal file
@@ -0,0 +1,94 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/LoveLosita/smartflow/backend/shared/respond"
|
||||
"google.golang.org/genproto/googleapis/rpc/errdetails"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// responseFromRPCError 负责把 task 的 gRPC 错误反解回项目内错误。
|
||||
//
|
||||
// 职责边界:
|
||||
// 1. 只在 gateway 边缘层使用;
|
||||
// 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 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 = "task zrpc service internal error"
|
||||
}
|
||||
return wrapRPCError(errors.New(msg))
|
||||
}
|
||||
|
||||
msg := strings.TrimSpace(st.Message())
|
||||
if msg == "" {
|
||||
msg = "task zrpc service rejected request"
|
||||
}
|
||||
return respond.Response{Status: grpcCodeToRespondStatus(st.Code()), Info: msg}
|
||||
}
|
||||
|
||||
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.NotFound:
|
||||
return respond.UserTasksEmpty.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("调用 task zrpc 服务失败: %w", err)
|
||||
}
|
||||
159
backend/client/taskclass/client.go
Normal file
159
backend/client/taskclass/client.go
Normal file
@@ -0,0 +1,159 @@
|
||||
package taskclass
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
taskclasspb "github.com/LoveLosita/smartflow/backend/services/task_class/rpc/pb"
|
||||
taskclasscontracts "github.com/LoveLosita/smartflow/backend/shared/contracts/taskclass"
|
||||
"github.com/zeromicro/go-zero/zrpc"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultEndpoint = "127.0.0.1:9086"
|
||||
defaultTimeout = 6 * time.Second
|
||||
)
|
||||
|
||||
type ClientConfig struct {
|
||||
Endpoints []string
|
||||
Target string
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// Client 是 gateway 访问 task-class zrpc 的最小适配层。
|
||||
//
|
||||
// 职责边界:
|
||||
// 1. 只负责跨进程 gRPC 调用和 JSON 透传,不触碰 DAO 或迁移期 schedule 直写细节;
|
||||
// 2. HTTP 入参仍由 gateway/api 做基础绑定,业务校验交给 task-class 服务;
|
||||
// 3. 复杂响应不在 gateway 重建模型,避免 DTO 复制扩散。
|
||||
type Client struct {
|
||||
rpc taskclasspb.TaskClassClient
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
client := &Client{rpc: taskclasspb.NewTaskClassClient(zclient.Conn())}
|
||||
if err := client.ping(timeout); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func (c *Client) AddTaskClass(ctx context.Context, req taskclasscontracts.UpsertTaskClassRequest) (json.RawMessage, error) {
|
||||
resp, err := c.callJSON(ctx, c.rpc.AddTaskClass, req)
|
||||
return jsonFromResponse(resp, err)
|
||||
}
|
||||
|
||||
func (c *Client) ListTaskClasses(ctx context.Context, userID int) (json.RawMessage, error) {
|
||||
resp, err := c.callJSON(ctx, c.rpc.ListTaskClasses, taskclasscontracts.UserRequest{UserID: userID})
|
||||
return jsonFromResponse(resp, err)
|
||||
}
|
||||
|
||||
func (c *Client) GetTaskClass(ctx context.Context, req taskclasscontracts.GetTaskClassRequest) (json.RawMessage, error) {
|
||||
resp, err := c.callJSON(ctx, c.rpc.GetTaskClass, req)
|
||||
return jsonFromResponse(resp, err)
|
||||
}
|
||||
|
||||
func (c *Client) UpdateTaskClass(ctx context.Context, req taskclasscontracts.UpsertTaskClassRequest) (json.RawMessage, error) {
|
||||
resp, err := c.callJSON(ctx, c.rpc.UpdateTaskClass, req)
|
||||
return jsonFromResponse(resp, err)
|
||||
}
|
||||
|
||||
func (c *Client) GetAgentTaskClasses(ctx context.Context, req taskclasscontracts.AgentTaskClassesRequest) (json.RawMessage, error) {
|
||||
resp, err := c.callJSON(ctx, c.rpc.GetAgentTaskClasses, req)
|
||||
return jsonFromResponse(resp, err)
|
||||
}
|
||||
|
||||
func (c *Client) InsertTaskClassItemIntoSchedule(ctx context.Context, req taskclasscontracts.InsertTaskClassItemIntoScheduleRequest) (json.RawMessage, error) {
|
||||
resp, err := c.callJSON(ctx, c.rpc.InsertTaskClassItemIntoSchedule, req)
|
||||
return jsonFromResponse(resp, err)
|
||||
}
|
||||
|
||||
func (c *Client) DeleteTaskClassItem(ctx context.Context, req taskclasscontracts.DeleteTaskClassItemRequest) (json.RawMessage, error) {
|
||||
resp, err := c.callJSON(ctx, c.rpc.DeleteTaskClassItem, req)
|
||||
return jsonFromResponse(resp, err)
|
||||
}
|
||||
|
||||
func (c *Client) DeleteTaskClass(ctx context.Context, req taskclasscontracts.DeleteTaskClassRequest) (json.RawMessage, error) {
|
||||
resp, err := c.callJSON(ctx, c.rpc.DeleteTaskClass, req)
|
||||
return jsonFromResponse(resp, err)
|
||||
}
|
||||
|
||||
func (c *Client) ApplyBatchIntoSchedule(ctx context.Context, req taskclasscontracts.ApplyBatchIntoScheduleRequest) (json.RawMessage, error) {
|
||||
resp, err := c.callJSON(ctx, c.rpc.ApplyBatchIntoSchedule, req)
|
||||
return jsonFromResponse(resp, err)
|
||||
}
|
||||
|
||||
func (c *Client) ensureReady() error {
|
||||
if c == nil || c.rpc == nil {
|
||||
return errors.New("task-class 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, &taskclasspb.StatusResponse{})
|
||||
return responseFromRPCError(err)
|
||||
}
|
||||
|
||||
func (c *Client) callJSON(ctx context.Context, fn func(context.Context, *taskclasspb.JSONRequest, ...grpc.CallOption) (*taskclasspb.JSONResponse, error), payload any) (*taskclasspb.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, &taskclasspb.JSONRequest{PayloadJson: raw})
|
||||
}
|
||||
|
||||
func jsonFromResponse(resp *taskclasspb.JSONResponse, rpcErr error) (json.RawMessage, error) {
|
||||
if rpcErr != nil {
|
||||
return nil, responseFromRPCError(rpcErr)
|
||||
}
|
||||
if resp == nil {
|
||||
return nil, errors.New("task-class 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
|
||||
}
|
||||
96
backend/client/taskclass/errors.go
Normal file
96
backend/client/taskclass/errors.go
Normal file
@@ -0,0 +1,96 @@
|
||||
package taskclass
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/LoveLosita/smartflow/backend/shared/respond"
|
||||
"google.golang.org/genproto/googleapis/rpc/errdetails"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// responseFromRPCError 负责把 task-class 的 gRPC 错误反解回项目内错误。
|
||||
//
|
||||
// 职责边界:
|
||||
// 1. 只在 gateway 边缘层使用;
|
||||
// 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 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 = "task-class zrpc service internal error"
|
||||
}
|
||||
return wrapRPCError(errors.New(msg))
|
||||
}
|
||||
|
||||
msg := strings.TrimSpace(st.Message())
|
||||
if msg == "" {
|
||||
msg = "task-class zrpc service rejected request"
|
||||
}
|
||||
return respond.Response{Status: grpcCodeToRespondStatus(st.Code()), Info: msg}
|
||||
}
|
||||
|
||||
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.PermissionDenied:
|
||||
return respond.ErrUnauthorized.Status
|
||||
case codes.InvalidArgument:
|
||||
return respond.MissingParam.Status
|
||||
case codes.NotFound:
|
||||
return respond.UserTaskClassNotFound.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("调用 task-class zrpc 服务失败: %w", err)
|
||||
}
|
||||
218
backend/client/userauth/client.go
Normal file
218
backend/client/userauth/client.go
Normal file
@@ -0,0 +1,218 @@
|
||||
package userauth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LoveLosita/smartflow/backend/services/userauth/rpc/pb"
|
||||
contracts "github.com/LoveLosita/smartflow/backend/shared/contracts/userauth"
|
||||
"github.com/zeromicro/go-zero/zrpc"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultEndpoint = "127.0.0.1:9081"
|
||||
defaultTimeout = 2 * time.Second
|
||||
)
|
||||
|
||||
type ClientConfig struct {
|
||||
Endpoints []string
|
||||
Target string
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// Client 是 gateway 侧 user/auth zrpc 的最小适配层。
|
||||
//
|
||||
// 职责边界:
|
||||
// 1. 只负责跨进程 gRPC 调用和响应转译,不碰 DB / Redis / JWT 细节;
|
||||
// 2. 服务端业务错误先通过 gRPC status 传输,再在这里反解回 respond.Response 风格;
|
||||
// 3. 上层调用方仍然可以保持 `res, err :=` 的统一用法。
|
||||
type Client struct {
|
||||
rpc pb.UserAuthClient
|
||||
}
|
||||
|
||||
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: pb.NewUserAuthClient(zclient.Conn())}, nil
|
||||
}
|
||||
|
||||
func (c *Client) Register(ctx context.Context, req contracts.RegisterRequest) (*contracts.RegisterResponse, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.Register(ctx, &pb.RegisterRequest{
|
||||
Username: req.Username,
|
||||
Password: req.Password,
|
||||
PhoneNumber: req.PhoneNumber,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, responseFromRPCError(err)
|
||||
}
|
||||
if resp == nil {
|
||||
return nil, errors.New("userauth zrpc service returned empty register response")
|
||||
}
|
||||
return &contracts.RegisterResponse{ID: uint(resp.Id)}, nil
|
||||
}
|
||||
|
||||
func (c *Client) Login(ctx context.Context, req contracts.LoginRequest) (*contracts.Tokens, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.Login(ctx, &pb.LoginRequest{
|
||||
Username: req.Username,
|
||||
Password: req.Password,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, responseFromRPCError(err)
|
||||
}
|
||||
return tokensFromResponse(resp)
|
||||
}
|
||||
|
||||
func (c *Client) RefreshToken(ctx context.Context, req contracts.RefreshTokenRequest) (*contracts.Tokens, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.RefreshToken(ctx, &pb.RefreshTokenRequest{
|
||||
RefreshToken: req.RefreshToken,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, responseFromRPCError(err)
|
||||
}
|
||||
return tokensFromResponse(resp)
|
||||
}
|
||||
|
||||
func (c *Client) Logout(ctx context.Context, accessToken string) error {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := c.rpc.Logout(ctx, &pb.LogoutRequest{
|
||||
AccessToken: accessToken,
|
||||
})
|
||||
if err != nil {
|
||||
return responseFromRPCError(err)
|
||||
}
|
||||
if resp == nil {
|
||||
return errors.New("userauth zrpc service returned empty logout response")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) ValidateAccessToken(ctx context.Context, accessToken string) (*contracts.ValidateAccessTokenResponse, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.ValidateAccessToken(ctx, &pb.ValidateAccessTokenRequest{
|
||||
AccessToken: accessToken,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, responseFromRPCError(err)
|
||||
}
|
||||
if resp == nil {
|
||||
return nil, errors.New("userauth zrpc service returned empty validate response")
|
||||
}
|
||||
return &contracts.ValidateAccessTokenResponse{
|
||||
Valid: resp.Valid,
|
||||
UserID: int(resp.UserId),
|
||||
TokenType: resp.TokenType,
|
||||
JTI: resp.Jti,
|
||||
ExpiresAt: timeFromUnixNano(resp.ExpiresAtUnixNano),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *Client) CheckTokenQuota(ctx context.Context, userID int) (*contracts.CheckTokenQuotaResponse, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.CheckTokenQuota(ctx, &pb.CheckTokenQuotaRequest{
|
||||
UserId: int64(userID),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, responseFromRPCError(err)
|
||||
}
|
||||
if resp == nil {
|
||||
return nil, errors.New("userauth zrpc service returned empty quota response")
|
||||
}
|
||||
return &contracts.CheckTokenQuotaResponse{
|
||||
Allowed: resp.Allowed,
|
||||
TokenLimit: int(resp.TokenLimit),
|
||||
TokenUsage: int(resp.TokenUsage),
|
||||
LastResetAt: timeFromUnixNano(resp.LastResetAtUnixNano),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *Client) AdjustTokenUsage(ctx context.Context, req contracts.AdjustTokenUsageRequest) (*contracts.CheckTokenQuotaResponse, error) {
|
||||
if err := c.ensureReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.rpc.AdjustTokenUsage(ctx, &pb.AdjustTokenUsageRequest{
|
||||
EventId: req.EventID,
|
||||
UserId: int64(req.UserID),
|
||||
TokenDelta: int64(req.TokenDelta),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, responseFromRPCError(err)
|
||||
}
|
||||
if resp == nil {
|
||||
return nil, errors.New("userauth zrpc service returned empty adjust response")
|
||||
}
|
||||
return &contracts.CheckTokenQuotaResponse{
|
||||
Allowed: resp.Allowed,
|
||||
TokenLimit: int(resp.TokenLimit),
|
||||
TokenUsage: int(resp.TokenUsage),
|
||||
LastResetAt: timeFromUnixNano(resp.LastResetAtUnixNano),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *Client) ensureReady() error {
|
||||
if c == nil || c.rpc == nil {
|
||||
return errors.New("userauth zrpc client is not initialized")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func tokensFromResponse(resp *pb.TokensResponse) (*contracts.Tokens, error) {
|
||||
if resp == nil {
|
||||
return nil, errors.New("userauth zrpc service returned empty token response")
|
||||
}
|
||||
return &contracts.Tokens{
|
||||
AccessToken: resp.AccessToken,
|
||||
RefreshToken: resp.RefreshToken,
|
||||
}, 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 timeFromUnixNano(value int64) time.Time {
|
||||
if value <= 0 {
|
||||
return time.Time{}
|
||||
}
|
||||
return time.Unix(0, value)
|
||||
}
|
||||
198
backend/client/userauth/errors.go
Normal file
198
backend/client/userauth/errors.go
Normal file
@@ -0,0 +1,198 @@
|
||||
package userauth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/LoveLosita/smartflow/backend/shared/respond"
|
||||
"google.golang.org/genproto/googleapis/rpc/errdetails"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// responseFromRPCError 负责把 user/auth 的 gRPC 错误反解回项目内的 respond.Response。
|
||||
//
|
||||
// 职责边界:
|
||||
// 1. 只在 gateway 边缘层使用,不下沉到服务实现里;
|
||||
// 2. 业务错误尽量恢复成 respond.Response,方便 API 层继续复用现有 DealWithError;
|
||||
// 3. 只要拿不到业务语义,就退化成普通 error,让上层按 500 处理。
|
||||
func responseFromRPCError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
st, ok := status.FromError(err)
|
||||
if !ok {
|
||||
return wrapRPCError(err)
|
||||
}
|
||||
|
||||
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 = "userauth zrpc service internal error"
|
||||
}
|
||||
return wrapRPCError(errors.New(msg))
|
||||
}
|
||||
|
||||
msg := strings.TrimSpace(st.Message())
|
||||
if msg == "" {
|
||||
msg = "userauth zrpc service rejected request"
|
||||
}
|
||||
return respond.Response{
|
||||
Status: grpcCodeToRespondStatus(st.Code()),
|
||||
Info: msg,
|
||||
}
|
||||
}
|
||||
|
||||
func responseFromStatus(st *status.Status) (respond.Response, bool) {
|
||||
if st == nil {
|
||||
return respond.Response{}, false
|
||||
}
|
||||
|
||||
if resp, ok := responseFromStatusDetails(st); ok {
|
||||
return resp, true
|
||||
}
|
||||
if resp, ok := responseFromLegacyStatus(st.Code(), st.Message()); ok {
|
||||
return resp, true
|
||||
}
|
||||
return respond.Response{}, false
|
||||
}
|
||||
|
||||
func responseFromStatusDetails(st *status.Status) (respond.Response, bool) {
|
||||
for _, detail := range st.Details() {
|
||||
info, ok := detail.(*errdetails.ErrorInfo)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
statusValue := strings.TrimSpace(info.Reason)
|
||||
if statusValue == "" {
|
||||
statusValue = grpcCodeToRespondStatus(st.Code())
|
||||
}
|
||||
if statusValue == "" {
|
||||
return respond.Response{}, false
|
||||
}
|
||||
|
||||
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 responseFromLegacyStatus(code codes.Code, message string) (respond.Response, bool) {
|
||||
trimmed := strings.TrimSpace(message)
|
||||
if resp, ok := respondResponseByMessage(trimmed); ok {
|
||||
return resp, true
|
||||
}
|
||||
|
||||
switch code {
|
||||
case codes.Unauthenticated:
|
||||
if trimmed == "" {
|
||||
trimmed = "unauthorized"
|
||||
}
|
||||
return respond.Response{Status: respond.ErrUnauthorized.Status, Info: trimmed}, true
|
||||
case codes.AlreadyExists:
|
||||
if trimmed == "" {
|
||||
trimmed = "already exists"
|
||||
}
|
||||
return respond.Response{Status: respond.InvalidName.Status, Info: trimmed}, true
|
||||
case codes.NotFound:
|
||||
if trimmed == "" {
|
||||
trimmed = "not found"
|
||||
}
|
||||
return respond.Response{Status: respond.WrongName.Status, Info: trimmed}, true
|
||||
case codes.ResourceExhausted:
|
||||
if trimmed == "" {
|
||||
trimmed = respond.TokenUsageExceedsLimit.Info
|
||||
}
|
||||
return respond.Response{Status: respond.TokenUsageExceedsLimit.Status, Info: trimmed}, true
|
||||
case codes.InvalidArgument:
|
||||
if trimmed == "" {
|
||||
trimmed = "invalid argument"
|
||||
}
|
||||
return respond.Response{Status: respond.MissingParam.Status, Info: trimmed}, true
|
||||
case codes.Internal, codes.Unknown, codes.DataLoss:
|
||||
if trimmed == "" {
|
||||
trimmed = "userauth service internal error"
|
||||
}
|
||||
return respond.InternalError(errors.New(trimmed)), true
|
||||
}
|
||||
|
||||
return respond.Response{}, false
|
||||
}
|
||||
|
||||
func respondResponseByMessage(message string) (respond.Response, bool) {
|
||||
switch strings.TrimSpace(message) {
|
||||
case respond.MissingParam.Info:
|
||||
return respond.MissingParam, true
|
||||
case respond.WrongParamType.Info:
|
||||
return respond.WrongParamType, true
|
||||
case respond.ParamTooLong.Info:
|
||||
return respond.ParamTooLong, true
|
||||
case respond.InvalidName.Info:
|
||||
return respond.InvalidName, true
|
||||
case respond.WrongName.Info:
|
||||
return respond.WrongName, true
|
||||
case respond.WrongPwd.Info:
|
||||
return respond.WrongPwd, true
|
||||
case respond.WrongUsernameOrPwd.Info:
|
||||
return respond.WrongUsernameOrPwd, true
|
||||
case respond.MissingToken.Info:
|
||||
return respond.MissingToken, true
|
||||
case respond.InvalidTokenSingingMethod.Info:
|
||||
return respond.InvalidTokenSingingMethod, true
|
||||
case respond.InvalidToken.Info:
|
||||
return respond.InvalidToken, true
|
||||
case respond.InvalidClaims.Info:
|
||||
return respond.InvalidClaims, true
|
||||
case respond.ErrUnauthorized.Info:
|
||||
return respond.ErrUnauthorized, true
|
||||
case respond.InvalidRefreshToken.Info:
|
||||
return respond.InvalidRefreshToken, true
|
||||
case respond.WrongTokenType.Info:
|
||||
return respond.WrongTokenType, true
|
||||
case respond.UserLoggedOut.Info:
|
||||
return respond.UserLoggedOut, true
|
||||
case respond.WrongUserID.Info:
|
||||
return respond.WrongUserID, true
|
||||
case respond.TokenUsageExceedsLimit.Info:
|
||||
return respond.TokenUsageExceedsLimit, true
|
||||
}
|
||||
return respond.Response{}, false
|
||||
}
|
||||
|
||||
func grpcCodeToRespondStatus(code codes.Code) string {
|
||||
switch code {
|
||||
case codes.Unauthenticated:
|
||||
return respond.ErrUnauthorized.Status
|
||||
case codes.AlreadyExists:
|
||||
return respond.InvalidName.Status
|
||||
case codes.NotFound:
|
||||
return respond.WrongName.Status
|
||||
case codes.ResourceExhausted:
|
||||
return respond.TokenUsageExceedsLimit.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("调用 userauth zrpc 服务失败: %w", err)
|
||||
}
|
||||
Reference in New Issue
Block a user