Skip to content

Commit f780126

Browse files
author
刘健
committed
Merge branch 'feature/openapi' into 'main'
fix: Nsq returns no error directly after parsing JSON exceptionNsq returns no... See merge request apipark/APIPark!159
2 parents b0c3791 + 7e7be7f commit f780126

File tree

12 files changed

+141
-19
lines changed

12 files changed

+141
-19
lines changed

app/ai-event-handler/nsq.go

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package main
33
import (
44
"context"
55
"encoding/json"
6+
"fmt"
67
"log"
78
"strings"
89
"time"
@@ -27,8 +28,8 @@ func init() {
2728
}
2829

2930
type NSQConfig struct {
30-
Addr string `json:"addr"`
31-
TopicPrefix string `json:"topic_prefix"`
31+
Addr string `json:"addr" yaml:"addr"`
32+
TopicPrefix string `json:"topic_prefix" yaml:"topic_prefix"`
3233
}
3334

3435
// 定义 NSQ 消息结构
@@ -78,6 +79,11 @@ func convertInt(value interface{}) int {
7879
}
7980
}
8081

82+
func genAIKey(key string, provider string) string {
83+
keys := strings.Split(key, "@")
84+
return strings.TrimSuffix(keys[0], fmt.Sprintf("-%s", provider))
85+
}
86+
8187
// HandleMessage 处理从 NSQ 读取的消息
8288
func (h *NSQHandler) HandleMessage(message *nsq.Message) error {
8389
log.Printf("Received message: %s", string(message.Body))
@@ -87,14 +93,14 @@ func (h *NSQHandler) HandleMessage(message *nsq.Message) error {
8793
err := json.Unmarshal(message.Body, &data)
8894
if err != nil {
8995
log.Printf("Failed to unmarshal message: %v", err)
90-
return err
96+
return nil
9197
}
9298

9399
// 将时间字符串转换为 time.Time
94100
timestamp, err := time.Parse(time.RFC3339, data.TimeISO8601)
95101
if err != nil {
96102
log.Printf("Failed to parse timestamp: %v", err)
97-
return err
103+
return nil
98104
}
99105

100106
day := time.Date(timestamp.Year(), timestamp.Month(), timestamp.Day(), 0, 0, 0, 0, timestamp.Location())
@@ -104,14 +110,13 @@ func (h *NSQHandler) HandleMessage(message *nsq.Message) error {
104110
finalStatus := &AIProviderStatus{}
105111
for _, s := range data.AI.ProviderStats {
106112
status := ToKeyStatus(s.Status).Int()
107-
keys := strings.Split(s.Key, "@")
108-
key := keys[0]
113+
key := genAIKey(s.Key, s.Provider)
109114
err = h.aiKeyService.Save(ctx, key, &ai_key.Edit{
110115
Status: &status,
111116
})
112117
if err != nil {
113118
log.Printf("Failed to save AI key: %v", err)
114-
return err
119+
return nil
115120
}
116121
if s.Provider != data.AI.Provider {
117122

@@ -128,11 +133,12 @@ func (h *NSQHandler) HandleMessage(message *nsq.Message) error {
128133
finalStatus = &s
129134
}
130135
if finalStatus != nil {
131-
keys := strings.Split(finalStatus.Key, "@")
132-
err = h.aiKeyService.IncrUseToken(ctx, keys[0], convertInt(data.AI.TotalToken))
136+
//keys := strings.Split(finalStatus.Key, "@")
137+
key := genAIKey(finalStatus.Key, finalStatus.Provider)
138+
err = h.aiKeyService.IncrUseToken(ctx, key, convertInt(data.AI.TotalToken))
133139
if err != nil {
134140
log.Printf("Failed to increment AI key token: %v", err)
135-
return err
141+
return nil
136142
}
137143
}
138144

@@ -151,7 +157,7 @@ func (h *NSQHandler) HandleMessage(message *nsq.Message) error {
151157
})
152158
if err != nil {
153159
log.Printf("Failed to call AI API: %v", err)
154-
return err
160+
return nil
155161
}
156162

157163
log.Printf("Message processed and saved to MySQL: %+v", data)

gateway/apinto/plugin/apinto_plugin.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
b: "subscription_service:#{application}"
2929
response:
3030
status_code: 403
31-
content_typ: "text/plan"
31+
content_type: "text/plan"
3232
charset: "utf-8"
3333
body: "Forbidden"
3434

init.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
_ "github.com/APIParkLab/APIPark/frontend"
66
_ "github.com/APIParkLab/APIPark/gateway/apinto"
77
_ "github.com/APIParkLab/APIPark/plugins/core"
8+
_ "github.com/APIParkLab/APIPark/plugins/openapi"
89
_ "github.com/APIParkLab/APIPark/plugins/permit"
910
_ "github.com/APIParkLab/APIPark/plugins/publish_flow"
1011
_ "github.com/APIParkLab/APIPark/resources/locale"

plugins/openapi/authorization.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package openapi
2+
3+
import (
4+
"net/http"
5+
6+
"github.com/eolinker/go-common/pm3"
7+
)
8+
9+
func (p *plugin) appAuthorizationApis() []pm3.Api {
10+
return []pm3.Api{
11+
pm3.CreateApiWidthDoc(http.MethodPost, "/openapi/v1/app/authorization", []string{"context", "query:app", "body"}, []string{"authorization"}, p.authorizationController.AddAuthorization),
12+
pm3.CreateApiWidthDoc(http.MethodPut, "/openapi/v1/app/authorization", []string{"context", "query:app", "query:authorization", "body"}, []string{"authorization"}, p.authorizationController.EditAuthorization),
13+
pm3.CreateApiWidthDoc(http.MethodDelete, "/openapi/v1/app/authorization", []string{"context", "query:app", "query:authorization"}, nil, p.authorizationController.DeleteAuthorization),
14+
pm3.CreateApiWidthDoc(http.MethodGet, "/openapi/v1/app/authorization", []string{"context", "query:app", "query:authorization"}, []string{"authorization"}, p.authorizationController.Info),
15+
pm3.CreateApiWidthDoc(http.MethodGet, "/openapi/v1/app/authorizations", []string{"context", "query:app"}, []string{"authorizations"}, p.authorizationController.Authorizations),
16+
pm3.CreateApiWidthDoc(http.MethodGet, "/openapi/v1/app/authorization/details", []string{"context", "query:app", "query:authorization"}, []string{"details"}, p.authorizationController.Detail),
17+
}
18+
}

plugins/openapi/check.go

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package openapi
2+
3+
import (
4+
"strings"
5+
6+
"github.com/eolinker/eosc/env"
7+
8+
"github.com/gin-gonic/gin"
9+
)
10+
11+
var (
12+
defaultAPIKey = "37eb0ebf"
13+
openCheck = newOpenapiCheck()
14+
)
15+
16+
type openapiCheck struct {
17+
apikey string
18+
}
19+
20+
func newOpenapiCheck() *openapiCheck {
21+
apikey, has := env.GetEnv("API_KEY")
22+
if !has {
23+
apikey = defaultAPIKey
24+
}
25+
return &openapiCheck{apikey: apikey}
26+
}
27+
28+
func (o *openapiCheck) Check(method string, path string) (bool, []gin.HandlerFunc) {
29+
if strings.HasPrefix(path, "/openapi/") {
30+
return true, []gin.HandlerFunc{o.Handler}
31+
}
32+
return false, nil
33+
}
34+
35+
func (o *openapiCheck) Sort() int {
36+
return -1
37+
}
38+
39+
func (o *openapiCheck) Handler(ginCtx *gin.Context) {
40+
authorization := ginCtx.GetHeader("Authorization")
41+
if authorization == "" {
42+
ginCtx.AbortWithStatusJSON(403, gin.H{"code": -8, "msg": "invalid token", "success": "fail"})
43+
return
44+
}
45+
}

plugins/openapi/driver.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package openapi
2+
3+
import (
4+
"github.com/eolinker/go-common/autowire"
5+
"github.com/eolinker/go-common/pm3"
6+
)
7+
8+
func init() {
9+
pm3.Register("openapi", new(Driver))
10+
}
11+
12+
type Driver struct {
13+
}
14+
15+
func (d *Driver) Create() (pm3.IPlugin, error) {
16+
p := new(plugin)
17+
autowire.Autowired(p)
18+
return p, nil
19+
}

plugins/openapi/plugin.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package openapi
2+
3+
import (
4+
application_authorization "github.com/APIParkLab/APIPark/controller/application-authorization"
5+
"github.com/eolinker/go-common/pm3"
6+
)
7+
8+
var (
9+
_ pm3.IPlugin = (*plugin)(nil)
10+
_ pm3.IPluginMiddleware = (*plugin)(nil)
11+
)
12+
13+
type plugin struct {
14+
apis []pm3.Api
15+
authorizationController application_authorization.IAuthorizationController `autowired:""`
16+
}
17+
18+
func (p *plugin) Middlewares() []pm3.IMiddleware {
19+
return []pm3.IMiddleware{
20+
openCheck,
21+
}
22+
}
23+
24+
func (p *plugin) APis() []pm3.Api {
25+
return p.apis
26+
}
27+
28+
func (p *plugin) Name() string {
29+
return "openapi"
30+
}
31+
func (p *plugin) OnComplete() {
32+
p.apis = p.appAuthorizationApis()
33+
}

resources/plugin/plugin.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
version: v7
1+
version: v8
22
sort:
33
- "access_log"
44
- "monitor"
@@ -41,7 +41,7 @@ plugin:
4141
b: "subscription_service:#{application}"
4242
response:
4343
status_code: 403
44-
content_typ: "text/plan"
44+
content_type: "text/plan"
4545
charset: "utf-8"
4646
body: "Forbidden"
4747

scripts/Dockerfile

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
88

99
ARG APP
1010

11-
ENV NSQ_ADDR=nsq:4150
12-
ENV NSQ_TOPIC_PREFIX=apipark
11+
ENV NSQ_ADDR=${APP}-nsq:4150
12+
ENV NSQ_TOPIC_PREFIX=${APP}
1313

1414
RUN mkdir -p /${APP}
1515

scripts/docker_build.sh

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ source ./scripts/common.sh
1717
APP="apipark"
1818

1919

20-
mkdir -p scripts/cmd/ && cp cmd/${APP} scripts/cmd/
20+
mkdir -p scripts/cmd/ && cp cmd/${APP} scripts/cmd/ && cp cmd/apipark_ai_event_listen scripts/cmd/
2121

2222
VERSION=$(gen_version)
2323

scripts/resource/docker_run.sh

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ echo -e " - $s" >> config.yml
2727
done
2828
echo -e "nsq:" >> config.yml
2929
echo -e " addr: ${NSQ_ADDR}" >> config.yml
30-
echo -e " topic: ${NSQ_TOPIC}" >> config.yml
30+
echo -e " topic_prefix: ${NSQ_TOPIC_PREFIX}" >> config.yml
3131
echo -e "port: 8288" >> config.yml
3232
echo -e "error_log:" >> config.yml
3333
echo -e " dir: ${ERROR_DIR}" >> config.yml

stores/ai/model.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ type Provider struct {
88
Name string `gorm:"type:varchar(100);not null;column:name;comment:name"`
99
DefaultLLM string `gorm:"type:varchar(255);not null;column:default_llm;comment:默认模型ID"`
1010
Config string `gorm:"type:text;not null;column:config;comment:配置信息"`
11-
Status int `gorm:"type:tinyint(1);not null;column:status;comment:状态,0:停用;1:启用,2:异常"`
11+
Status int `gorm:"type:tinyint(1);not null;column:status;comment:状态,0:停用;1:启用,2:异常;default:1"`
1212
Priority int `gorm:"type:int;not null;column:priority;comment:优先级,值越小优先级越高"`
1313
Creator string `gorm:"size:36;not null;column:creator;comment:创建人;index:creator" aovalue:"creator"` // 创建人
1414
Updater string `gorm:"size:36;not null;column:updater;comment:更新人;index:updater" aovalue:"updater"` // 更新人

0 commit comments

Comments
 (0)