Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .github/workflows/build_image.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,13 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v4

# set up Go
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: "1.26"
check-latest: true

# download Go modules
- name: Download Go modules
run: go mod download
Expand Down
8 changes: 6 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,8 @@ pnpm dev

- **前端界面**: http://localhost:3000
- **API 文档**: http://localhost:8000/swagger/index.html
- **健康检查**: http://localhost:8000/api/health
- **健康检查**: http://localhost:8000/api/v1/health
- **就绪检查**: http://localhost:8000/api/v1/ready

## ⚙️ 配置说明

Expand All @@ -140,6 +141,8 @@ pnpm dev
| 配置项 | 说明 | 示例 |
|--------|------|------|
| `app.addr` | 后端服务监听地址 | `:8000` |
| `worker.port` | Worker 探针端口 | `8001` |
| `schedule.port` | Beat/Scheduler 探针端口 | `8002` |
| `oauth2.client_id` | OAuth2 客户端 ID | `your_client_id` |
| `database.host` | MySQL 数据库地址 | `127.0.0.1` |
| `redis.host` | Redis 服务器地址 | `127.0.0.1` |
Expand Down Expand Up @@ -196,7 +199,8 @@ http://localhost:8000/swagger/index.html

### 主要 API 端点

- `GET /api/health` - 健康检查
- `GET /api/v1/health` - 健康检查
- `GET /api/v1/ready` - 就绪检查
- `GET /api/oauth2/login` - OAuth2 登录
- `GET /api/projects` - 获取项目列表
- `POST /api/projects` - 创建新项目
Expand Down
2 changes: 2 additions & 0 deletions config.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -96,13 +96,15 @@ log:

# Schedule
schedule:
port: 8002 # beat/scheduler probe port
user_badge_score_dispatch_interval_seconds: 1
update_user_badges_scores_task_cron: "0 2 * * *"
update_all_badges_task_cron: "0 1 * * *"
expire_stale_payment_orders_cron: "*/1 * * * *" # 扫描超时未付款订单的频率

# Worker
worker:
port: 8001 # worker probe port
concurrency: 50

# linuxDo
Expand Down
27 changes: 27 additions & 0 deletions docs/docs.go
Original file line number Diff line number Diff line change
Expand Up @@ -677,6 +677,24 @@ const docTemplate = `{
}
}
},
"/api/v1/ready": {
"get": {
"produces": [
"application/json"
],
"tags": [
"health"
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/health.ReadyResponse"
}
}
}
}
},
"/api/v1/tags": {
"get": {
"consumes": [
Expand Down Expand Up @@ -817,6 +835,15 @@ const docTemplate = `{
}
}
},
"health.ReadyResponse": {
"type": "object",
"properties": {
"data": {},
"error_msg": {
"type": "string"
}
}
},
"oauth.BasicUserInfo": {
"type": "object",
"properties": {
Expand Down
27 changes: 27 additions & 0 deletions docs/swagger.json
Original file line number Diff line number Diff line change
Expand Up @@ -668,6 +668,24 @@
}
}
},
"/api/v1/ready": {
"get": {
"produces": [
"application/json"
],
"tags": [
"health"
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/health.ReadyResponse"
}
}
}
}
},
"/api/v1/tags": {
"get": {
"consumes": [
Expand Down Expand Up @@ -808,6 +826,15 @@
}
}
},
"health.ReadyResponse": {
"type": "object",
"properties": {
"data": {},
"error_msg": {
"type": "string"
}
}
},
"oauth.BasicUserInfo": {
"type": "object",
"properties": {
Expand Down
17 changes: 17 additions & 0 deletions docs/swagger.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,12 @@ definitions:
error_msg:
type: string
type: object
health.ReadyResponse:
properties:
data: {}
error_msg:
type: string
type: object
oauth.BasicUserInfo:
properties:
avatar_url:
Expand Down Expand Up @@ -892,6 +898,17 @@ paths:
$ref: '#/definitions/project.ListReceiveHistoryChartResponse'
tags:
- project
/api/v1/ready:
get:
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/health.ReadyResponse'
tags:
- health
/api/v1/tags:
get:
consumes:
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module github.com/linux-do/cdk

go 1.24
go 1.26

require (
github.com/ClickHouse/clickhouse-go/v2 v2.23.2
Expand Down
53 changes: 52 additions & 1 deletion internal/apps/health/routers.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,12 @@
package health

import (
"github.com/gin-gonic/gin"
"net/http"

"github.com/gin-gonic/gin"
"github.com/linux-do/cdk/internal/config"
"github.com/linux-do/cdk/internal/db"
"github.com/linux-do/cdk/internal/logger"
)

type HealthResponse struct {
Expand All @@ -42,3 +46,50 @@ type HealthResponse struct {
func Health(c *gin.Context) {
c.JSON(http.StatusOK, HealthResponse{})
}

type ReadyResponse struct {
ErrorMsg string `json:"error_msg"`
Data interface{} `json:"data"`
}

// Ready godoc
// @Tags health
// @Produce json
// @Success 200 {object} ReadyResponse
// @Router /api/v1/ready [get]
func Ready(c *gin.Context) {
// init
ctx := c.Request.Context()
// check mysql
if config.Config.Database.Enabled {
sqlDB, err := db.DB(ctx).DB()
if err != nil {
logger.ErrorF(c.Request.Context(), "[Ready] mysql check failed: %s", err.Error())
c.AbortWithStatusJSON(http.StatusInternalServerError, ReadyResponse{})
return
}
if err := sqlDB.PingContext(ctx); err != nil {
logger.ErrorF(c.Request.Context(), "[Ready] mysql check failed: %s", err.Error())
c.AbortWithStatusJSON(http.StatusInternalServerError, ReadyResponse{})
return
}
}
// check redis
if config.Config.Redis.Enabled {
if err := db.Redis.Ping(ctx).Err(); err != nil {
logger.ErrorF(c.Request.Context(), "[Ready] redis check failed: %s", err.Error())
c.AbortWithStatusJSON(http.StatusInternalServerError, ReadyResponse{})
return
}
}
// check clickhouse
if config.Config.ClickHouse.Enabled {
if err := db.ChConn.Ping(ctx); err != nil {
logger.ErrorF(c.Request.Context(), "[Ready] clickhouse check failed: %s", err.Error())
c.AbortWithStatusJSON(http.StatusInternalServerError, ReadyResponse{})
return
}
}
// response
c.JSON(http.StatusOK, ReadyResponse{})
}
10 changes: 8 additions & 2 deletions internal/cmd/scheduler.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,12 @@
package cmd

import (
"github.com/linux-do/cdk/internal/task/schedule"
"log"

"github.com/linux-do/cdk/internal/config"
"github.com/linux-do/cdk/internal/probe"
"github.com/linux-do/cdk/internal/task/schedule"

"github.com/spf13/cobra"
)

Expand All @@ -36,8 +39,11 @@ var schedulerCmd = &cobra.Command{
Short: "CDK Scheduler",
Run: func(cmd *cobra.Command, args []string) {
log.Println("[Scheduler] 启动定时任务调度服务")
if err := probe.Start(config.Config.Schedule.Port); err != nil {
log.Fatalf("[Scheduler] 启动探针服务失败: %v", err)
}
if err := schedule.StartScheduler(); err != nil {
log.Fatalf("[调度器] 启动失败: %v", err)
log.Fatalf("[Scheduler] 启动失败: %v", err)
}
},
}
10 changes: 8 additions & 2 deletions internal/cmd/worker.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,12 @@
package cmd

import (
"github.com/linux-do/cdk/internal/task/worker"
"log"

"github.com/linux-do/cdk/internal/config"
"github.com/linux-do/cdk/internal/probe"
"github.com/linux-do/cdk/internal/task/worker"

"github.com/spf13/cobra"
)

Expand All @@ -36,8 +39,11 @@ var workerCmd = &cobra.Command{
Short: "CDK Worker",
Run: func(cmd *cobra.Command, args []string) {
log.Println("[Worker] 启动任务处理服务")
if err := probe.Start(config.Config.Worker.Port); err != nil {
log.Fatalf("[Worker] 启动探针服务失败: %v", err)
}
if err := worker.StartWorker(); err != nil {
log.Fatalf("[工作器] 启动失败: %v", err)
log.Fatalf("[Worker] 启动失败: %v", err)
}
},
}
2 changes: 2 additions & 0 deletions internal/config/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ type logConfig struct {

// scheduleConfig 定时任务配置
type scheduleConfig struct {
Port int `mapstructure:"port"`
UserBadgeScoreDispatchIntervalSeconds int `mapstructure:"user_badge_score_dispatch_interval_seconds"`
UpdateUserBadgeScoresTaskCron string `mapstructure:"update_user_badges_scores_task_cron"`
UpdateAllBadgesTaskCron string `mapstructure:"update_all_badges_task_cron"`
Expand All @@ -142,6 +143,7 @@ type scheduleConfig struct {

// workerConfig 工作配置
type workerConfig struct {
Port int `mapstructure:"port"`
Concurrency int `mapstructure:"concurrency"`
}

Expand Down
76 changes: 76 additions & 0 deletions internal/probe/server.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*
* MIT License
*
* Copyright (c) 2025 linux.do
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

package probe

import (
"errors"
"fmt"
"log"
"net"
"net/http"
"strconv"
"time"

"github.com/gin-gonic/gin"
"github.com/linux-do/cdk/internal/apps/health"
"github.com/linux-do/cdk/internal/config"
)

func Start(port int) error {
if port <= 0 {
return fmt.Errorf("invalid probe port: %d", port)
}
if config.Config.App.Env == "production" {
gin.SetMode(gin.ReleaseMode)
}

addr := net.JoinHostPort("", strconv.Itoa(port))
listener, err := net.Listen("tcp", addr)
if err != nil {
return err
}

engine := gin.New()
engine.Use(gin.Recovery())
apiV1Router := engine.Group(config.Config.App.APIPrefix + "/v1")
{
apiV1Router.GET("/health", health.Health)
apiV1Router.GET("/ready", health.Ready)
}

server := &http.Server{
Handler: engine,
ReadHeaderTimeout: 5 * time.Second,
}

go func() {
if errServe := server.Serve(listener); errServe != nil && !errors.Is(errServe, http.ErrServerClosed) {
log.Printf("[Probe] serve failed: %v\n", errServe)
}
}()

log.Printf("[Probe] listening on :%d\n", port)
return nil
}
Loading
Loading