diff --git a/controller/channel.go b/controller/channel.go index 01bd112e69..7c12cdd9b3 100644 --- a/controller/channel.go +++ b/controller/channel.go @@ -697,17 +697,18 @@ type AddChannelRequest struct { Channel *model.Channel `json:"channel"` } -func getVertexArrayKeys(keys string) ([]string, error) { +func getVertexArrayKeys(keys string) ([]string, []int, error) { if keys == "" { - return nil, nil + return nil, nil, nil } var keyArray []any err := common.Unmarshal([]byte(keys), &keyArray) if err != nil { - return nil, common.NewMessage("Batch-adding Vertex AI keys requires a JSON array, for example {{example}}. Check the input: {{error}}", map[string]any{"example": "[{key1}, {key2}...]", "error": err.Error()}) + return nil, nil, common.NewMessage("Batch-adding Vertex AI keys requires a JSON array, for example {{example}}. Check the input: {{error}}", map[string]any{"example": "[{key1}, {key2}...]", "error": err.Error()}) } cleanKeys := make([]string, 0, len(keyArray)) - for _, key := range keyArray { + inputIndices := make([]int, 0, len(keyArray)) + for i, key := range keyArray { var keyStr string switch v := key.(type) { case string: @@ -715,18 +716,19 @@ func getVertexArrayKeys(keys string) ([]string, error) { default: bytes, err := common.Marshal(v) if err != nil { - return nil, common.NewMessage("Failed to encode Vertex AI key JSON: {{error}}", map[string]any{"error": err.Error()}) + return nil, nil, common.NewMessage("Failed to encode Vertex AI key JSON: {{error}}", map[string]any{"error": err.Error()}) } keyStr = string(bytes) } if keyStr != "" { cleanKeys = append(cleanKeys, keyStr) + inputIndices = append(inputIndices, i) } } if len(cleanKeys) == 0 { - return nil, common.NewMessage("Vertex AI keys for batch adding cannot be empty") + return nil, nil, common.NewMessage("Vertex AI keys for batch adding cannot be empty") } - return cleanKeys, nil + return cleanKeys, inputIndices, nil } func AddChannel(c *gin.Context) { @@ -760,26 +762,29 @@ func AddChannel(c *gin.Context) { addChannelRequest.Channel.CreatedTime = common.GetTimestamp() keys := make([]string, 0) + inputIndices := make([]int, 0) switch addChannelRequest.Mode { case "multi_to_single": addChannelRequest.Channel.ChannelInfo.IsMultiKey = true addChannelRequest.Channel.ChannelInfo.MultiKeyMode = addChannelRequest.MultiKeyMode if addChannelRequest.Channel.Type == constant.ChannelTypeVertexAi && addChannelRequest.Channel.GetOtherSettings().VertexKeyType != dto.VertexKeyTypeAPIKey { - array, err := getVertexArrayKeys(addChannelRequest.Channel.Key) + array, indices, err := getVertexArrayKeys(addChannelRequest.Channel.Key) if err != nil { common.ApiError(c, err) return } addChannelRequest.Channel.ChannelInfo.MultiKeySize = len(array) addChannelRequest.Channel.Key = strings.Join(array, "\n") + inputIndices = indices } else { cleanKeys := make([]string, 0) - for key := range strings.SplitSeq(addChannelRequest.Channel.Key, "\n") { + for i, key := range strings.Split(addChannelRequest.Channel.Key, "\n") { if key == "" { continue } key = strings.TrimSpace(key) cleanKeys = append(cleanKeys, key) + inputIndices = append(inputIndices, i) } addChannelRequest.Channel.ChannelInfo.MultiKeySize = len(cleanKeys) addChannelRequest.Channel.Key = strings.Join(cleanKeys, "\n") @@ -788,23 +793,28 @@ func AddChannel(c *gin.Context) { case "batch": if addChannelRequest.Channel.Type == constant.ChannelTypeVertexAi && addChannelRequest.Channel.GetOtherSettings().VertexKeyType != dto.VertexKeyTypeAPIKey { // multi json - keys, err = getVertexArrayKeys(addChannelRequest.Channel.Key) + keys, inputIndices, err = getVertexArrayKeys(addChannelRequest.Channel.Key) if err != nil { common.ApiError(c, err) return } } else { keys = strings.Split(addChannelRequest.Channel.Key, "\n") + for i := range keys { + inputIndices = append(inputIndices, i) + } } case "single": keys = []string{addChannelRequest.Channel.Key} + inputIndices = []int{0} default: common.ApiErrorT(c, "Unsupported add mode") return } channels := make([]model.Channel, 0, len(keys)) - for _, key := range keys { + channelInputIndices := make([][]int, 0, len(keys)) + for i, key := range keys { if key == "" { continue } @@ -818,6 +828,11 @@ func AddChannel(c *gin.Context) { localChannel.Name = fmt.Sprintf("%s %s", localChannel.Name, keyPrefix) } channels = append(channels, *localChannel) + if addChannelRequest.Mode == "multi_to_single" { + channelInputIndices = append(channelInputIndices, inputIndices) + } else { + channelInputIndices = append(channelInputIndices, []int{inputIndices[i]}) + } } err = model.BatchInsertChannels(channels) if err != nil { @@ -833,9 +848,22 @@ func AddChannel(c *gin.Context) { createAudit["base_url_source"] = "plugin_default" } recordManageAudit(c, "channel.create", createAudit) + ids := make([]int, len(channels)) + results := make([]gin.H, 0, len(inputIndices)) + for i, channel := range channels { + ids[i] = channel.Id + for _, inputIndex := range channelInputIndices[i] { + results = append(results, gin.H{"input_index": inputIndex, "channel_id": channel.Id}) + } + } + data := gin.H{"ids": ids, "results": results} + if len(ids) == 1 { + data["id"] = ids[0] + } c.JSON(http.StatusOK, gin.H{ "success": true, "message": "", + "data": data, }) return } @@ -1172,7 +1200,7 @@ func UpdateChannel(c *gin.Context) { if channel.Type == constant.ChannelTypeVertexAi && channel.GetOtherSettings().VertexKeyType != dto.VertexKeyTypeAPIKey { // 尝试解析新密钥为JSON数组 if strings.HasPrefix(strings.TrimSpace(channel.Key), "[") { - array, err := getVertexArrayKeys(channel.Key) + array, _, err := getVertexArrayKeys(channel.Key) if err != nil { common.ApiErrorT(c, "Failed to parse appended keys: {{error}}", map[string]any{"error": err.Error()}) return diff --git a/controller/channel_create_test.go b/controller/channel_create_test.go new file mode 100644 index 0000000000..04fdc26a3a --- /dev/null +++ b/controller/channel_create_test.go @@ -0,0 +1,260 @@ +package controller + +import ( + "fmt" + "net/http" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/QuantumNous/new-api/common" + "github.com/QuantumNous/new-api/constant" + "github.com/QuantumNous/new-api/model" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gorm.io/gorm" +) + +func setupChannelCreateTest(t *testing.T) int { + t.Helper() + previousDB, previousLogDB := model.DB, model.LOG_DB + previousType, previousLogType := common.MainDatabaseType(), common.LogDatabaseType() + previousMaster, previousCache, previousRedis, previousSQLite := common.IsMasterNode, common.MemoryCacheEnabled, common.RedisEnabled, common.SQLitePath + t.Cleanup(func() { + model.DB, model.LOG_DB = previousDB, previousLogDB + common.SetDatabaseTypes(previousType, previousLogType) + common.IsMasterNode, common.MemoryCacheEnabled, common.RedisEnabled, common.SQLitePath = previousMaster, previousCache, previousRedis, previousSQLite + }) + t.Setenv("SQL_DSN", os.Getenv("TEST_CHANNEL_SQL_DSN")) + t.Setenv("LOG_SQL_DSN", "") + common.IsMasterNode, common.MemoryCacheEnabled, common.RedisEnabled = false, false, false + common.SQLitePath = filepath.Join(t.TempDir(), "channel.db") + require.NoError(t, model.InitDB()) + database := model.DB + sqlDB, err := database.DB() + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, sqlDB.Close()) }) + model.LOG_DB = database + common.SetLogDatabaseType(common.MainDatabaseType()) + require.NoError(t, database.AutoMigrate(&model.Channel{}, &model.Ability{}, &model.User{}, &model.Log{}, &model.AuditLog{})) + root := &model.User{Username: "channel-create-review-root", Role: common.RoleRootUser, Status: common.UserStatusEnabled} + require.NoError(t, database.Create(root).Error) + t.Cleanup(func() { require.NoError(t, database.Unscoped().Delete(root).Error) }) + versionQuery := "SELECT VERSION()" + if common.UsingMainDatabase(common.DatabaseTypeSQLite) { + versionQuery = "SELECT sqlite_version()" + } + var version string + require.NoError(t, database.Raw(versionQuery).Scan(&version).Error) + t.Logf("database=%s version=%s", common.MainDatabaseType(), version) + return root.Id +} + +func TestAddChannelReturnsCreatedIDs(t *testing.T) { + rootID := setupChannelCreateTest(t) + const firstKey, secondKey = "sk-create-id-first", "sk-create-id-second" + const vertexArray = `["", {"project_id":"one"}, " \n ", " {\"project_id\":\"two\"} ", {"project_id":"one"}, null, 42]` + vertexKeys := []string{`{"project_id":"one"}`, `{"project_id":"two"}`, `{"project_id":"one"}`, "null", "42"} + const vertexSingle = `{ + "project_id": "single", + "type": "service_account" +}` + batchKeys := make([]string, 51) + batchIndices := make([]int, len(batchKeys)) + for i := range batchKeys { + batchKeys[i] = fmt.Sprintf("sk-create-id-%02d", i) + batchIndices[i] = i + 1 + } + for _, tc := range []struct { + name string + mode string + key string + channelType int + settings string + wantKeys []string + wantInputIndices []int + }{ + {name: "single", mode: "single", key: firstKey, wantKeys: []string{firstKey}, wantInputIndices: []int{0}}, + {name: "batch duplicate keys", mode: "batch", key: "\n" + firstKey + "\n\n" + firstKey + "\n" + secondKey, wantKeys: []string{firstKey, firstKey, secondKey}, wantInputIndices: []int{1, 3, 4}}, + {name: "batch one channel", mode: "batch", key: firstKey + "\n", wantKeys: []string{firstKey}, wantInputIndices: []int{0}}, + {name: "batch preserves whitespace", mode: "batch", key: "\n \n" + firstKey, wantKeys: []string{" ", firstKey}, wantInputIndices: []int{1, 2}}, + {name: "multi to single", mode: "multi_to_single", key: "\n " + firstKey + " \n\n" + secondKey + "\n", wantKeys: []string{firstKey + "\n" + secondKey}, wantInputIndices: []int{1, 3}}, + {name: "multi preserves trimmed blank", mode: "multi_to_single", key: firstKey + "\n \n" + secondKey, wantKeys: []string{firstKey + "\n\n" + secondKey}, wantInputIndices: []int{0, 1, 2}}, + {name: "multi whitespace only", mode: "multi_to_single", key: " ", wantKeys: []string{}, wantInputIndices: []int{}}, + {name: "multiple chunks", mode: "batch", key: "\n" + strings.Join(batchKeys, "\n"), wantKeys: batchKeys, wantInputIndices: batchIndices}, + {name: "empty batch", mode: "batch", key: "\n", wantKeys: []string{}, wantInputIndices: []int{}}, + {name: "vertex array", mode: "batch", key: vertexArray, channelType: constant.ChannelTypeVertexAi, wantKeys: vertexKeys, wantInputIndices: []int{1, 3, 4, 5, 6}}, + {name: "vertex multi", mode: "multi_to_single", key: vertexArray, channelType: constant.ChannelTypeVertexAi, wantKeys: []string{strings.Join(vertexKeys, "\n")}, wantInputIndices: []int{1, 3, 4, 5, 6}}, + {name: "single multiline json", mode: "single", key: vertexSingle, channelType: constant.ChannelTypeVertexAi, wantKeys: []string{vertexSingle}, wantInputIndices: []int{0}}, + {name: "vertex api key batch", mode: "batch", key: "\n" + firstKey + "\n\n" + secondKey, channelType: constant.ChannelTypeVertexAi, settings: `{"vertex_key_type":"api_key"}`, wantKeys: []string{firstKey, secondKey}, wantInputIndices: []int{1, 3}}, + } { + t.Run(tc.name, func(t *testing.T) { + name := "created-id-" + tc.name + existing := &model.Channel{Name: name, Type: 1, Key: firstKey, Models: "test-model", Group: "default"} + require.NoError(t, existing.Insert()) + t.Cleanup(func() { + var ids []int + require.NoError(t, model.DB.Model(&model.Channel{}).Where("name = ?", name).Pluck("id", &ids).Error) + _, err := model.BatchDeleteChannels(ids) + require.NoError(t, err) + }) + channel := &model.Channel{Name: name, Type: tc.channelType, Key: tc.key, Models: "test-model", Group: "default", OtherSettings: tc.settings} + if channel.Type == 0 { + channel.Type = constant.ChannelTypeOpenAI + } + if channel.Type == constant.ChannelTypeVertexAi { + channel.Other = `{"default":"us-central1"}` + } + request, err := common.Marshal(AddChannelRequest{Mode: tc.mode, Channel: channel}) + require.NoError(t, err) + response := postAddChannel(t, rootID, common.RoleRootUser, string(request)) + require.Equal(t, http.StatusOK, response.Code) + var result struct { + Success bool `json:"success"` + Message string `json:"message"` + Data struct { + ID *int `json:"id"` + IDs []int `json:"ids"` + Results []struct { + InputIndex int `json:"input_index"` + ChannelID int `json:"channel_id"` + } `json:"results"` + } `json:"data"` + } + require.NoError(t, common.Unmarshal(response.Body.Bytes(), &result)) + require.True(t, result.Success, response.Body.String()) + assert.Empty(t, result.Message) + require.NotNil(t, result.Data.IDs, "empty creations must return an array, not null") + require.Len(t, result.Data.IDs, len(tc.wantKeys)) + assert.NotContains(t, result.Data.IDs, existing.Id) + var created []model.Channel + require.NoError(t, model.DB.Where("name = ? AND id <> ?", name, existing.Id).Order("id").Find(&created).Error) + require.Len(t, created, len(tc.wantKeys)) + for i, channel := range created { + assert.Positive(t, result.Data.IDs[i]) + assert.Equal(t, channel.Id, result.Data.IDs[i]) + assert.Equal(t, tc.wantKeys[i], channel.Key) + assert.Equal(t, tc.mode == "multi_to_single", channel.ChannelInfo.IsMultiKey) + } + require.NotNil(t, result.Data.Results, "empty creations must return an empty results array") + require.Len(t, result.Data.Results, len(tc.wantInputIndices)) + results := make([]map[string]int, 0, len(tc.wantInputIndices)) + for i, inputIndex := range tc.wantInputIndices { + channelIndex := i + if tc.mode == "multi_to_single" { + channelIndex = 0 + } + assert.Equal(t, inputIndex, result.Data.Results[i].InputIndex) + assert.Equal(t, created[channelIndex].Id, result.Data.Results[i].ChannelID) + results = append(results, map[string]int{"input_index": inputIndex, "channel_id": created[channelIndex].Id}) + } + if tc.mode == "multi_to_single" && len(created) == 1 { + assert.Equal(t, len(tc.wantInputIndices), created[0].ChannelInfo.MultiKeySize) + } + data := map[string]any{"ids": result.Data.IDs, "results": results} + if len(created) == 1 { + require.NotNil(t, result.Data.ID) + assert.Equal(t, created[0].Id, *result.Data.ID) + data["id"] = created[0].Id + } else { + assert.Nil(t, result.Data.ID) + } + expected, err := common.Marshal(map[string]any{"success": true, "message": "", "data": data}) + require.NoError(t, err) + assert.JSONEq(t, string(expected), response.Body.String(), "the response must contain only IDs, not channel credentials") + }) + } +} + +func TestAddChannelInvalidVertexBatchDoesNotReturnResults(t *testing.T) { + rootID := setupChannelCreateTest(t) + for _, mode := range []string{"batch", "multi_to_single"} { + for _, key := range []string{"[]", `["", " "]`, "[{"} { + t.Run(mode+"/"+key, func(t *testing.T) { + request, err := common.Marshal(AddChannelRequest{Mode: mode, Channel: &model.Channel{ + Name: "invalid-vertex-array", Type: constant.ChannelTypeVertexAi, Key: key, + Models: "test-model", Group: "default", Other: `{"default":"us-central1"}`, + }}) + require.NoError(t, err) + response := postAddChannel(t, rootID, common.RoleRootUser, string(request)) + assert.Equal(t, http.StatusOK, response.Code) + var result map[string]any + require.NoError(t, common.Unmarshal(response.Body.Bytes(), &result)) + assert.Equal(t, false, result["success"]) + assert.NotEmpty(t, result["message"]) + assert.NotContains(t, result, "data") + var count int64 + require.NoError(t, model.DB.Model(&model.Channel{}).Where("name = ?", "invalid-vertex-array").Count(&count).Error) + assert.Zero(t, count) + }) + } + } +} + +func TestAddChannelRollbackDoesNotReturnIDs(t *testing.T) { + rootID := setupChannelCreateTest(t) + // Force a real database error in the second chunk, after the first 50 rows + // received IDs. This constraint exists only in the isolated test database. + column := `"key"` + if common.UsingMainDatabase(common.DatabaseTypeMySQL) { + column = "`key`(191)" + } + const indexName = "channel_create_test_unique_key" + require.NoError(t, model.DB.Exec("CREATE UNIQUE INDEX "+indexName+" ON channels ("+column+")").Error) + t.Cleanup(func() { require.NoError(t, model.DB.Migrator().DropIndex(&model.Channel{}, indexName)) }) + keys := make([]string, 51) + for i := range keys[:50] { + keys[i] = fmt.Sprintf("sk-create-rollback-%02d", i) + } + keys[50] = keys[0] + request, err := common.Marshal(AddChannelRequest{Mode: "batch", Channel: &model.Channel{ + Name: "created-id-rollback", Type: 1, Key: strings.Join(keys, "\n"), Models: "test-model", Group: "default", + }}) + require.NoError(t, err) + response := postAddChannel(t, rootID, common.RoleRootUser, string(request)) + assert.Equal(t, http.StatusOK, response.Code) + var result map[string]any + require.NoError(t, common.Unmarshal(response.Body.Bytes(), &result)) + assert.Equal(t, false, result["success"]) + assert.NotEmpty(t, result["message"]) + assert.NotContains(t, result, "data") + var channels, abilities int64 + require.NoError(t, model.DB.Model(&model.Channel{}).Where("name = ?", "created-id-rollback").Count(&channels).Error) + require.NoError(t, model.DB.Model(&model.Ability{}).Count(&abilities).Error) + assert.Zero(t, channels) + assert.Zero(t, abilities) +} + +func TestAddChannelPanicRollsBackWithoutSuccess(t *testing.T) { + rootID := setupChannelCreateTest(t) + database := model.DB + channelCreates := 0 + const callback = "test:channel-create-panic" + require.NoError(t, database.Callback().Create().Before("gorm:create").Register(callback, func(tx *gorm.DB) { + if tx.Statement.Table == "channels" { + channelCreates++ + if channelCreates == 2 { + panic("second channel chunk failed") + } + } + })) + t.Cleanup(func() { require.NoError(t, database.Callback().Create().Remove(callback)) }) + keys := make([]string, 51) + for i := range keys { + keys[i] = fmt.Sprintf("sk-create-panic-%02d", i) + } + request, err := common.Marshal(AddChannelRequest{Mode: "batch", Channel: &model.Channel{ + Name: "created-id-panic", Type: 1, Key: strings.Join(keys, "\n"), Models: "test-model", Group: "default", + }}) + require.NoError(t, err) + require.PanicsWithValue(t, "second channel chunk failed", func() { + postAddChannel(t, rootID, common.RoleRootUser, string(request)) + }, "a rolled-back transaction must not reach the success response") + assert.Equal(t, 2, channelCreates) + var channels, abilities int64 + require.NoError(t, database.Model(&model.Channel{}).Where("name = ?", "created-id-panic").Count(&channels).Error) + require.NoError(t, database.Model(&model.Ability{}).Count(&abilities).Error) + assert.Zero(t, channels) + assert.Zero(t, abilities) +} diff --git a/docs/openapi/api.json b/docs/openapi/api.json index 8f5bc89e9b..a7c3042440 100644 --- a/docs/openapi/api.json +++ b/docs/openapi/api.json @@ -2727,8 +2727,148 @@ }, "responses": { "200": { - "description": "成功", - "headers": {} + "description": "创建成功时返回本次新建渠道的 ID;业务失败仍使用 HTTP 200,success 为 false 且不返回 data。", + "headers": {}, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "message": { + "type": "string" + }, + "data": { + "type": "object", + "description": "仅创建成功时返回,不包含渠道凭证。", + "properties": { + "ids": { + "type": "array", + "description": "本次实际新建渠道的 ID,按创建顺序排列。single 和 multi_to_single 最多创建一个渠道,batch 可创建多个;按现有规则过滤后未创建渠道时为 []。", + "items": { + "type": "integer" + } + }, + "id": { + "type": "integer", + "description": "仅本次恰好新建一个渠道时返回,与 ids[0] 相同。" + }, + "results": { + "type": "array", + "description": "原始输入与新建渠道的对应关系;按输入顺序返回,不含 Key。被现有规则过滤掉的输入不返回条目;未创建渠道时为 []。multi_to_single 的多个输入会对应同一个 channel_id。", + "items": { + "type": "object", + "properties": { + "input_index": { + "type": "integer", + "minimum": 0, + "description": "从 0 开始的原始输入位置。single 的整个 channel.key(含多行 JSON)为输入 0;batch/multi_to_single 普通 Key 与 Vertex API Key 使用原始换行分割位置;Vertex 服务账号 JSON 使用原始数组下标。下标保留被过滤空项占用的位置,不重新编号。" + }, + "channel_id": { + "type": "integer", + "description": "该输入对应的本次新建渠道 ID。" + } + }, + "required": [ + "input_index", + "channel_id" + ] + } + } + }, + "required": [ + "ids", + "results" + ] + } + }, + "required": [ + "success", + "message" + ] + }, + "examples": { + "single": { + "summary": "新建一个渠道", + "value": { + "success": true, + "message": "", + "data": { + "ids": [ + 12345 + ], + "id": 12345, + "results": [ + { + "input_index": 0, + "channel_id": 12345 + } + ] + } + } + }, + "batch": { + "summary": "批量新建渠道(原始第 0、2 项为空,被过滤)", + "value": { + "success": true, + "message": "", + "data": { + "ids": [ + 12345, + 12346 + ], + "results": [ + { + "input_index": 1, + "channel_id": 12345 + }, + { + "input_index": 3, + "channel_id": 12346 + } + ] + } + } + }, + "empty": { + "summary": "批次过滤空 Key 后未创建渠道", + "value": { + "success": true, + "message": "", + "data": { + "ids": [], + "results": [] + } + } + }, + "multi_to_single": { + "summary": "多个输入合并为一个渠道(原始第 1 项为空,被过滤)", + "value": { + "success": true, + "message": "", + "data": { + "ids": [ + 12345 + ], + "id": 12345, + "results": [ + { + "input_index": 0, + "channel_id": 12345 + }, + { + "input_index": 2, + "channel_id": 12345 + } + ] + } + } + } + } + } + } } }, "security": [ diff --git a/model/channel.go b/model/channel.go index 202f51cb4a..3262a5ad6d 100644 --- a/model/channel.go +++ b/model/channel.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "math/rand" + "slices" "strings" "sync" @@ -465,10 +466,12 @@ func BatchInsertChannels(channels []Channel) error { defer func() { if r := recover(); r != nil { tx.Rollback() + panic(r) } }() - for _, chunk := range lo.Chunk(channels, 50) { + // Keep each chunk backed by channels so generated IDs reach the caller. + for chunk := range slices.Chunk(channels, 50) { if err := tx.Create(&chunk).Error; err != nil { tx.Rollback() return err