Version: 0.9.70.dev.260504
后端:
1. 阶段 5 schedule 首刀服务化落地,新增 `cmd/schedule`、`services/schedule/{dao,rpc,sv,core}`、`gateway/client/schedule`、`shared/contracts/schedule` 和 schedule port
2. gateway `/api/v1/schedule/*` 切到 schedule zrpc client,HTTP 门面只保留鉴权、参数绑定、超时和轻量转发
3. active-scheduler 的 schedule facts、feedback 和 confirm apply 改为调用 schedule RPC adapter,减少对 `schedule_events`、`schedules`、`task_classes`、`task_items` 的跨域 DB 依赖
4. 单体聊天主动调度 rerun 的 schedule 读写链路切到 schedule RPC,迁移期仅保留 task facts 直读 Gorm
5. 为 schedule zrpc 补充 `Ping` 启动健康检查,并在 gateway client 与 active-scheduler adapter 初始化时校验服务可用
6. `cmd/schedule` 独立初始化 DB / Redis,只 AutoMigrate schedule 自有表,并显式检查迁移期 task / task-class 依赖表
7. 更新 active-scheduler 依赖表检查和 preview confirm apply 抽象,保留旧 Gorm 实现作为迁移期回退路径
8. 补充 `schedule.rpc` 示例配置和 schedule HTTP RPC 超时配置
文档:
1. 更新微服务迁移计划,将阶段 5 schedule 首刀进展、当前切流点、旧实现保留范围和 active-scheduler DB 依赖收缩情况写入基线
This commit is contained in:
@@ -6,19 +6,21 @@ import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/LoveLosita/smartflow/backend/model"
|
||||
"github.com/LoveLosita/smartflow/backend/respond"
|
||||
"github.com/LoveLosita/smartflow/backend/service"
|
||||
schedulecontracts "github.com/LoveLosita/smartflow/backend/shared/contracts/schedule"
|
||||
"github.com/LoveLosita/smartflow/backend/shared/ports"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const scheduleRequestTimeout = 6 * time.Second
|
||||
|
||||
type ScheduleAPI struct {
|
||||
scheduleService *service.ScheduleService
|
||||
scheduleClient ports.ScheduleCommandClient
|
||||
}
|
||||
|
||||
func NewScheduleAPI(scheduleService *service.ScheduleService) *ScheduleAPI {
|
||||
func NewScheduleAPI(scheduleClient ports.ScheduleCommandClient) *ScheduleAPI {
|
||||
return &ScheduleAPI{
|
||||
scheduleService: scheduleService,
|
||||
scheduleClient: scheduleClient,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,9 +28,9 @@ func (s *ScheduleAPI) GetUserTodaySchedule(c *gin.Context) {
|
||||
// 1. 从请求上下文中获取用户ID
|
||||
userID := c.GetInt("user_id")
|
||||
//2.调用服务层方法获取用户当天的日程安排
|
||||
ctx, cancel := context.WithTimeout(c.Request.Context(), 1*time.Second)
|
||||
ctx, cancel := context.WithTimeout(c.Request.Context(), scheduleRequestTimeout)
|
||||
defer cancel() // 记得释放资源
|
||||
todaySchedules, err := s.scheduleService.GetUserTodaySchedule(ctx, userID)
|
||||
todaySchedules, err := s.scheduleClient.GetUserTodaySchedule(ctx, userID)
|
||||
if err != nil {
|
||||
respond.DealWithError(c, err)
|
||||
return
|
||||
@@ -47,9 +49,9 @@ func (s *ScheduleAPI) GetUserWeeklySchedule(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
//3.调用服务层方法获取用户当周的日程安排
|
||||
ctx, cancel := context.WithTimeout(c.Request.Context(), 1*time.Second)
|
||||
ctx, cancel := context.WithTimeout(c.Request.Context(), scheduleRequestTimeout)
|
||||
defer cancel() // 记得释放资源
|
||||
weeklySchedules, err := s.scheduleService.GetUserWeeklySchedule(ctx, userID, week)
|
||||
weeklySchedules, err := s.scheduleClient.GetUserWeeklySchedule(ctx, userID, week)
|
||||
if err != nil {
|
||||
respond.DealWithError(c, err)
|
||||
return
|
||||
@@ -62,15 +64,18 @@ func (s *ScheduleAPI) DeleteScheduleEvent(c *gin.Context) {
|
||||
// 1. 从请求上下文中获取用户ID
|
||||
userID := c.GetInt("user_id")
|
||||
// 2. 从请求体中获取要删除的日程事件信息
|
||||
var req []model.UserDeleteScheduleEvent
|
||||
var req []schedulecontracts.UserDeleteScheduleEvent
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, respond.WrongParamType)
|
||||
return
|
||||
}
|
||||
//3.调用服务层方法删除指定的日程事件
|
||||
ctx, cancel := context.WithTimeout(c.Request.Context(), 1*time.Second)
|
||||
ctx, cancel := context.WithTimeout(c.Request.Context(), scheduleRequestTimeout)
|
||||
defer cancel() // 记得释放资源
|
||||
err := s.scheduleService.DeleteScheduleEvent(ctx, req, userID)
|
||||
err := s.scheduleClient.DeleteScheduleEvent(ctx, schedulecontracts.DeleteScheduleEventsRequest{
|
||||
UserID: userID,
|
||||
Events: req,
|
||||
})
|
||||
if err != nil {
|
||||
respond.DealWithError(c, err)
|
||||
return
|
||||
@@ -95,9 +100,13 @@ func (s *ScheduleAPI) GetUserRecentCompletedSchedules(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
//2.调用服务层方法获取用户最近完成的日程事件
|
||||
ctx, cancel := context.WithTimeout(c.Request.Context(), 1*time.Second)
|
||||
ctx, cancel := context.WithTimeout(c.Request.Context(), scheduleRequestTimeout)
|
||||
defer cancel() // 记得释放资源
|
||||
completedSchedules, err := s.scheduleService.GetUserRecentCompletedSchedules(ctx, userID, intIndex, intLimit)
|
||||
completedSchedules, err := s.scheduleClient.GetUserRecentCompletedSchedules(ctx, schedulecontracts.RecentCompletedRequest{
|
||||
UserID: userID,
|
||||
Index: intIndex,
|
||||
Limit: intLimit,
|
||||
})
|
||||
if err != nil {
|
||||
respond.DealWithError(c, err)
|
||||
return
|
||||
@@ -110,9 +119,9 @@ func (s *ScheduleAPI) GetUserOngoingSchedule(c *gin.Context) {
|
||||
// 1. 从请求上下文中获取用户ID
|
||||
userID := c.GetInt("user_id")
|
||||
//2.调用服务层方法获取用户正在进行的日程事件
|
||||
ctx, cancel := context.WithTimeout(c.Request.Context(), 1*time.Second)
|
||||
ctx, cancel := context.WithTimeout(c.Request.Context(), scheduleRequestTimeout)
|
||||
defer cancel() // 记得释放资源
|
||||
ongoingSchedule, err := s.scheduleService.GetUserOngoingSchedule(ctx, userID)
|
||||
ongoingSchedule, err := s.scheduleClient.GetUserOngoingSchedule(ctx, userID)
|
||||
if err != nil {
|
||||
respond.DealWithError(c, err)
|
||||
return
|
||||
@@ -132,7 +141,12 @@ func (s *ScheduleAPI) UserRevocateTaskItemFromSchedule(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
//3.调用服务层方法撤销任务块的安排
|
||||
err = s.scheduleService.RevocateUserTaskClassItem(context.Background(), userID, intEventID)
|
||||
ctx, cancel := context.WithTimeout(c.Request.Context(), scheduleRequestTimeout)
|
||||
defer cancel()
|
||||
err = s.scheduleClient.RevokeTaskItemFromSchedule(ctx, schedulecontracts.RevokeTaskItemRequest{
|
||||
UserID: userID,
|
||||
EventID: intEventID,
|
||||
})
|
||||
if err != nil {
|
||||
respond.DealWithError(c, err)
|
||||
return
|
||||
@@ -152,9 +166,12 @@ func (s *ScheduleAPI) SmartPlanning(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
//3.调用服务层方法进行智能规划
|
||||
ctx, cancel := context.WithTimeout(c.Request.Context(), 1*time.Second)
|
||||
ctx, cancel := context.WithTimeout(c.Request.Context(), scheduleRequestTimeout)
|
||||
defer cancel() // 记得释放资源
|
||||
res, err := s.scheduleService.SmartPlanning(ctx, userID, intTaskClassID)
|
||||
res, err := s.scheduleClient.SmartPlanning(ctx, schedulecontracts.SmartPlanningRequest{
|
||||
UserID: userID,
|
||||
TaskClassID: intTaskClassID,
|
||||
})
|
||||
if err != nil {
|
||||
respond.DealWithError(c, err)
|
||||
return
|
||||
@@ -174,16 +191,21 @@ func (s *ScheduleAPI) SmartPlanningMulti(c *gin.Context) {
|
||||
userID := c.GetInt("user_id")
|
||||
|
||||
// 2. 绑定多任务类请求体。
|
||||
var req model.UserSmartPlanningMultiRequest
|
||||
var req struct {
|
||||
TaskClassIDs []int `json:"task_class_ids" binding:"required,min=1,dive,min=1"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, respond.WrongParamType)
|
||||
return
|
||||
}
|
||||
|
||||
// 3. 调用服务层执行多任务类粗排。
|
||||
ctx, cancel := context.WithTimeout(c.Request.Context(), 1*time.Second)
|
||||
ctx, cancel := context.WithTimeout(c.Request.Context(), scheduleRequestTimeout)
|
||||
defer cancel()
|
||||
res, err := s.scheduleService.SmartPlanningMulti(ctx, userID, req.TaskClassIDs)
|
||||
res, err := s.scheduleClient.SmartPlanningMulti(ctx, schedulecontracts.SmartPlanningMultiRequest{
|
||||
UserID: userID,
|
||||
TaskClassIDs: req.TaskClassIDs,
|
||||
})
|
||||
if err != nil {
|
||||
respond.DealWithError(c, err)
|
||||
return
|
||||
|
||||
190
backend/gateway/client/schedule/client.go
Normal file
190
backend/gateway/client/schedule/client.go
Normal file
@@ -0,0 +1,190 @@
|
||||
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) 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/gateway/client/schedule/errors.go
Normal file
92
backend/gateway/client/schedule/errors.go
Normal file
@@ -0,0 +1,92 @@
|
||||
package schedule
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/LoveLosita/smartflow/backend/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)
|
||||
}
|
||||
Reference in New Issue
Block a user