Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

add log hooks (#21822)

Jin Haib955316c7175
diff --git a/internal/common/model.go b/internal/common/model.go
index 590f0ec241..13fb2398d6 100644
--- a/internal/common/model.go
+++ b/internal/common/model.go
@@ -51,23 +51,6 @@ func (m *ModelUsage) String() string {
return fmt.Sprintf("%#v", m)
}
-type OperationLog struct {
- EventTime time.Time `json:"event_time"`
- UserID string `json:"user_id"`
- UserName string `json:"user_name"`
- IPAddress string `json:"ip_address"`
- Operation string `json:"operation"`
- APIPath string `json:"api_path"`
- HTTPMethod string `json:"http_method"`
- ResourceType string `json:"resource_type"`
- ResourceID string `json:"resource_id"`
- ResourceName string `json:"resource_name"`
- RequestParams string `json:"request_params"`
- Code int `json:"code"`
- Error error `json:"error"`
- DurationMS int64 `json:"duration_ms"`
-}
-
func ParseCompositeModelName(compositeName string) (modelName, instanceName, providerName string, err error) {
parts := strings.Split(compositeName, "@")
switch len(parts) {
@@ -86,16 +69,3 @@ func ParseCompositeModelName(compositeName string) (modelName, instanceName, pro
n := len(parts)
return strings.Join(parts[:n-2], "@"), parts[n-2], parts[n-1], nil
}
-
-type IngestLog struct {
- EventTime time.Time `json:"event_time"`
- UserID string `json:"user_id"`
- UserName string `json:"user_name"`
- Worker string `json:"worker"`
- TaskID string `json:"task_id"`
- Filename string `json:"filename"`
- Code int `json:"code"`
- Error error `json:"error"`
- DurationMS int64 `json:"duration_ms"`
- Operation map[string]any `json:"operation"`
-}
diff --git a/internal/common/stub.go b/internal/common/stub.go
index 70a9243130..dcab51e087 100644
--- a/internal/common/stub.go
+++ b/internal/common/stub.go
@@ -19,6 +19,8 @@
package common
import (
+ "time"
+
"go.uber.org/zap"
)
@@ -36,6 +38,20 @@ func InitAudit(logType string, file FileOutput, serviceName string) error {
return nil
}
+type OperationLog struct {
+ EventTime time.Time `json:"event_time"`
+ UserID string `json:"user_id"`
+ IPAddress string `json:"ip_address"`
+ Operation string `json:"operation"`
+ APIPath string `json:"api_path"`
+ HTTPMethod string `json:"http_method"`
+ RequestParams string `json:"request_params"`
+ Resources map[string]any `json:"resources"`
+ Code int `json:"code"`
+ Error error `json:"error"`
+ DurationMS int64 `json:"duration_ms"`
+}
+
func Audit(operationLog *OperationLog, fields ...zap.Field) {
}
@@ -43,6 +59,19 @@ func InitIngestLog(logType string, file FileOutput, serviceName string) error {
return nil
}
-func LogIngest(fields ...zap.Field) {
-
+type IngestionLog struct {
+ EventTime time.Time `json:"event_time"`
+ UserID string `json:"user_id"`
+ UserName string `json:"user_name"`
+ DocumentID string `json:"document_id"`
+ Worker string `json:"worker"`
+ TaskID string `json:"task_id"`
+ TaskType string `json:"task_type"`
+ Filename string `json:"filename"`
+ Code int `json:"code"`
+ Error error `json:"error"`
+ DurationMS int64 `json:"duration_ms"`
+ Operation map[string]any `json:"operation"`
}
+
+func LogIngest(log *IngestionLog, fields ...zap.Field) {}
diff --git a/internal/handler/agent.go b/internal/handler/agent.go
index 4a2ca50b2b..557d6303c0 100644
--- a/internal/handler/agent.go
+++ b/internal/handler/agent.go
@@ -292,21 +292,17 @@ func mapAgentError(err error) (common.ErrorCode, string) {
// @Success 200 {object} entity.UserCanvas
// @Router /api/v1/agents [post]
func (h *AgentHandler) CreateAgent(c *gin.Context) {
- quotaUser, ok := billingQuotaUser(c)
- if !ok {
+ user, errorCode, err := billingQuotaUser(c)
+ if err != nil {
+ common.ErrorWithCode(c, errorCode, err.Error())
return
}
- if !billingEnforceApps(c, quotaUser.ID) {
+ if !billingEnforceApps(c, user.ID) {
return
}
- user, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.ErrorWithCode(c, errorCode, errorMessage)
- return
- }
var req service.CreateAgentRequest
- if err := decodeJSONWithNumber(c.Request.Body, &req); err != nil && !errors.Is(err, io.EOF) {
+ if err = decodeJSONWithNumber(c.Request.Body, &req); err != nil && !errors.Is(err, io.EOF) {
common.ResponseWithCodeData(c, common.CodeArgumentError, nil, "Invalid request: "+err.Error())
return
}
diff --git a/internal/handler/chat.go b/internal/handler/chat.go
index 2434290e0b..532db75869 100644
--- a/internal/handler/chat.go
+++ b/internal/handler/chat.go
@@ -68,8 +68,6 @@ type ChatMindMapRequest struct {
// @Summary List Chats
// @Description Get list of chats (dialogs) for the current user
// @Tags chat
-// @Accept json
-// @Produce json
// @Success 200 {object} service.ListChatsResponse
// @Router /api/v1/chats [get]
func (h *ChatHandler) ListChats(c *gin.Context) {
@@ -107,12 +105,12 @@ func (h *ChatHandler) ListChats(c *gin.Context) {
// `sort` supersedes the older pair, so a request it can order is not rejected
// for the spelling of an `orderby` that will not be read.
sortTerms := sortTermsFromQuery(c)
- orderby := c.DefaultQuery("orderby", "create_time")
+ orderBy := c.DefaultQuery("orderby", "create_time")
if len(sortTerms) == 0 {
- switch orderby {
+ switch orderBy {
case "create_time", "update_time", "name":
default:
- common.ResponseWithCodeData(c, common.CodeArgumentError, nil, fmt.Sprintf("invalid orderby field: %s", orderby))
+ common.ResponseWithCodeData(c, common.CodeArgumentError, nil, fmt.Sprintf("invalid orderby field: %s", orderBy))
return
}
}
@@ -121,7 +119,7 @@ func (h *ChatHandler) ListChats(c *gin.Context) {
if descStr := c.Query("desc"); descStr != "" {
desc = !strings.EqualFold(descStr, "false")
}
- terms := orderTerms(sortTerms, orderby, desc)
+ terms := orderTerms(sortTerms, orderBy, desc)
ownerIDs := getOwnerIDs(c)
ctx := c.Request.Context()
@@ -143,17 +141,16 @@ func (h *ChatHandler) ListChats(c *gin.Context) {
// @Summary Create Chat
// @Description Create a chat, aligned with Python POST /api/v1/chats.
// @Tags chat
-// @Accept json
-// @Produce json
// @Param request body service.CreateChatRequest true "chat configuration"
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/chats [post]
func (h *ChatHandler) Create(c *gin.Context) {
- quotaUser, ok := billingQuotaUser(c)
- if !ok {
+ user, errorCode, err := billingQuotaUser(c)
+ if err != nil {
+ common.ErrorWithCode(c, errorCode, err.Error())
return
}
- if !billingEnforceApps(c, quotaUser.ID) {
+ if !billingEnforceApps(c, user.ID) {
return
}
@@ -166,7 +163,7 @@ func (h *ChatHandler) Create(c *gin.Context) {
var req map[string]interface{}
decoder := json.NewDecoder(c.Request.Body)
decoder.UseNumber()
- if err := decoder.Decode(&req); err != nil {
+ if err = decoder.Decode(&req); err != nil {
common.ResponseWithCodeData(c, common.CodeArgumentError, nil, err.Error())
return
}
@@ -188,8 +185,6 @@ func (h *ChatHandler) Create(c *gin.Context) {
// @Summary Generate Chat Mind Map
// @Description Retrieves related chunks and asks the configured chat model to summarize them into a mind map.
// @Tags chat
-// @Accept json
-// @Produce json
// @Param request body ChatMindMapRequest true "Mind map parameters"
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/chat/mindmap [post]
@@ -341,8 +336,6 @@ func (h *ChatHandler) BulkDeleteChats(c *gin.Context) {
// @Summary Get Chat Detail
// @Description Get detail of a chat by ID
// @Tags chat
-// @Accept json
-// @Produce json
// @Param chat_id path string true "chat ID"
// @Success 200 {object} service.GetChatResponse
// @Router /api/v1/chats/{chat_id} [get]
diff --git a/internal/handler/dataset.go b/internal/handler/dataset.go
index 57d98c4af4..23c7f32275 100644
--- a/internal/handler/dataset.go
+++ b/internal/handler/dataset.go
@@ -27,6 +27,7 @@ import (
"sort"
"strconv"
"strings"
+ "time"
"github.com/gin-gonic/gin"
@@ -198,7 +199,7 @@ func (h *DatasetsHandler) ListDatasets(c *gin.Context) {
}
}
if len(duplicates) > 0 {
- common.ResponseWithCodeData(c, common.CodeArgumentError, nil, fmt.Sprintf("Duplicate ids: '%s'", strings.Join(duplicates, ", ")))
+ common.ResponseWithCodeData(c, common.CodeArgumentError, nil, fmt.Sprintf("duplicate ids: '%s'", strings.Join(duplicates, ", ")))
return
}
}
@@ -233,38 +234,67 @@ func (h *DatasetsHandler) ListDatasets(c *gin.Context) {
// CreateDataset handles POST /api/v1/datasets.
func (h *DatasetsHandler) CreateDataset(c *gin.Context) {
+ startAt := time.Now()
+ operationLog := &common.OperationLog{
+ EventTime: startAt,
+ Operation: "create_dataset",
+ APIPath: c.FullPath(),
+ HTTPMethod: c.Request.Method,
+ IPAddress: c.ClientIP(),
+ }
+ defer func() {
+ operationLog.DurationMS = time.Since(startAt).Milliseconds()
+ common.Audit(operationLog)
+ }()
+
user, errorCode, errorMessage := GetUser(c)
if errorCode != common.CodeSuccess {
common.ErrorWithCode(c, errorCode, errorMessage)
+ operationLog.Code = int(errorCode)
+ operationLog.Error = errors.New(errorMessage)
return
}
+ operationLog.UserID = user.ID
- bodyBytes, raw, ok := parseJSONRequestObject(c)
- if !ok {
+ bodyBytes, raw, err := parseJSONRequestObject(c)
+ if err != nil {
+ operationLog.Code = int(common.CodeArgumentError)
+ operationLog.Error = err
return
}
if _, exists := raw["ext"]; exists {
- common.ResponseWithCodeData(c, common.CodeArgumentError, nil, "Extra inputs are not permitted: ext")
+ err = fmt.Errorf("extra inputs are not permitted: ext")
+ common.ErrorWithCode(c, common.CodeArgumentError, err.Error())
+ operationLog.Code = int(common.CodeArgumentError)
+ operationLog.Error = err
return
}
for field := range raw {
if !createDatasetAllowedFields[field] {
- common.ResponseWithCodeData(c, common.CodeArgumentError, nil, fmt.Sprintf("Extra inputs are not permitted: %s", field))
+ err = fmt.Errorf("extra inputs are not permitted: %s", field)
+ common.ErrorWithCode(c, common.CodeArgumentError, err.Error())
+ operationLog.Code = int(common.CodeArgumentError)
+ operationLog.Error = err
return
}
}
var req service.CreateDatasetRequest
- if err := json.Unmarshal(bodyBytes, &req); err != nil {
- common.ResponseWithCodeData(c, common.CodeDataError, nil, err.Error())
+ if err = json.Unmarshal(bodyBytes, &req); err != nil {
+ common.ErrorWithCode(c, common.CodeDataError, err.Error())
+ operationLog.Code = int(common.CodeDataError)
+ operationLog.Error = err
return
}
if req.ParserConfig == nil && req.PipelineID == nil {
req.ParserConfig = map[string]interface{}{}
}
- // Mirror Python's pydantic required validation.
+
if req.Name == "" || (len(bodyBytes) > 0 && jsonNullValue(bodyBytes, "name")) {
- common.ResponseWithCodeData(c, common.CodeDataError, nil, "Field validation for 'name' failed on the 'required' tag")
+ err = fmt.Errorf("field validation for 'name' failed on the 'required' tag")
+ common.ErrorWithCode(c, common.CodeDataError, err.Error())
+ operationLog.Code = int(common.CodeDataError)
+ operationLog.Error = err
return
}
@@ -286,9 +316,13 @@ func (h *DatasetsHandler) CreateDataset(c *gin.Context) {
"current": insufficient.Current,
"limit": insufficient.Limit,
})
+ operationLog.Code = int(common.CodeBillingAppsInsufficient)
+ operationLog.Error = insufficient
return
}
common.ErrorWithCode(c, common.CodeServerError, quotaErr.Error())
+ operationLog.Code = int(common.CodeServerError)
+ operationLog.Error = quotaErr
return
}
}
@@ -299,6 +333,8 @@ func (h *DatasetsHandler) CreateDataset(c *gin.Context) {
})
if err != nil {
common.ErrorWithCode(c, code, err.Error())
+ operationLog.Code = int(code)
+ operationLog.Error = err
return
}
@@ -339,31 +375,31 @@ func parsePythonBool(s string) (bool, bool) {
}
// parseJSONRequestObject mirrors Python's validate_and_parse_json_request:
-// content-type check first, then JSON syntax, then object shape. On failure it
+// content-type check first, then JSON syntax, then object shape. On failure, it
// writes the error response and returns ok=false.
-func parseJSONRequestObject(c *gin.Context) (body []byte, raw map[string]interface{}, ok bool) {
+func parseJSONRequestObject(c *gin.Context) ([]byte, map[string]interface{}, error) {
if c.ContentType() != "application/json" {
common.ResponseWithCodeData(c, common.CodeArgumentError, nil, fmt.Sprintf("Unsupported content type: Expected application/json, got %s", c.GetHeader("Content-Type")))
- return nil, nil, false
+ return nil, nil, fmt.Errorf("unsupported content type: Expected application/json, got %s", c.GetHeader("Content-Type"))
}
body, err := c.GetRawData()
if err != nil || len(body) == 0 {
common.ResponseWithCodeData(c, common.CodeArgumentError, nil, "Malformed JSON syntax: Missing commas/brackets or invalid encoding")
- return nil, nil, false
+ return nil, nil, fmt.Errorf("malformed JSON syntax: Missing commas/brackets or invalid encoding")
}
var payload interface{}
- if err := json.Unmarshal(body, &payload); err != nil {
+ if err = json.Unmarshal(body, &payload); err != nil {
common.ResponseWithCodeData(c, common.CodeArgumentError, nil, "Malformed JSON syntax: Missing commas/brackets or invalid encoding")
- return nil, nil, false
+ return nil, nil, err
}
raw, isObject := payload.(map[string]interface{})
if !isObject {
common.ResponseWithCodeData(c, common.CodeArgumentError, nil, fmt.Sprintf("Invalid request payload: expected object, got %s", pythonJSONTypeName(payload)))
- return nil, nil, false
+ return nil, nil, fmt.Errorf("invalid request payload: expected object, got %s", pythonJSONTypeName(payload))
}
- return body, raw, true
+ return body, raw, nil
}
// jsonNullValue checks if a field is explicitly null in the JSON body.
@@ -424,57 +460,87 @@ var updateDatasetAllowedFields = map[string]bool{
}
func (h *DatasetsHandler) UpdateDataset(c *gin.Context) {
+ startAt := time.Now()
+ operationLog := &common.OperationLog{
+ EventTime: startAt,
+ Operation: "create_dataset",
+ APIPath: c.FullPath(),
+ HTTPMethod: c.Request.Method,
+ IPAddress: c.ClientIP(),
+ }
+ defer func() {
+ operationLog.DurationMS = time.Since(startAt).Milliseconds()
+ common.Audit(operationLog)
+ }()
+
user, errorCode, errorMessage := GetUser(c)
if errorCode != common.CodeSuccess {
common.ErrorWithCode(c, errorCode, errorMessage)
+ operationLog.Code = int(errorCode)
+ operationLog.Error = errors.New(errorMessage)
return
}
userID := strings.TrimSpace(user.ID)
if userID == "" {
common.ResponseWithCodeData(c, common.CodeDataError, nil, "user id is required")
+ operationLog.Code = int(common.CodeDataError)
+ operationLog.Error = errors.New("user id is required")
return
}
datasetID := strings.TrimSpace(c.Param("dataset_id"))
if datasetID == "" {
common.ResponseWithCodeData(c, common.CodeBadRequest, nil, "dataset id is required")
+ operationLog.Code = int(common.CodeBadRequest)
+ operationLog.Error = errors.New("dataset id is required")
return
}
- // Mirror the pydantic UUID validation of Python's UpdateDatasetReq.
+
if _, err := dataset.NormalizeDatasetID(datasetID); err != nil {
common.ResponseWithCodeData(c, common.CodeArgumentError, nil, err.Error())
+ operationLog.Code = int(common.CodeArgumentError)
+ operationLog.Error = err
return
}
- bodyBytes, _, ok := parseJSONRequestObject(c)
- if !ok {
+ bodyBytes, _, err := parseJSONRequestObject(c)
+ if err != nil {
+ common.ErrorWithCode(c, common.CodeArgumentError, err.Error())
+ operationLog.Code = int(common.CodeArgumentError)
+ operationLog.Error = err
return
}
var req service.UpdateDatasetRequest
- if err := json.Unmarshal(bodyBytes, &req); err != nil {
+ if err = json.Unmarshal(bodyBytes, &req); err != nil {
common.ResponseWithCodeData(c, common.CodeDataError, nil, err.Error())
+ operationLog.Code = int(common.CodeDataError)
+ operationLog.Error = err
return
}
// Detect an explicitly provided parser_config key (even {} or null) so it is not
// rejected as "no properties were modified", mirroring the Python contract.
var providedFields map[string]json.RawMessage
- if err := json.Unmarshal(bodyBytes, &providedFields); err == nil {
+ if err = json.Unmarshal(bodyBytes, &providedFields); err == nil {
_, req.ParserConfigProvided = providedFields["parser_config"]
// Mirror pydantic's extra="forbid" on UpdateDatasetReq.
for field := range providedFields {
if !updateDatasetAllowedFields[field] {
common.ResponseWithCodeData(c, common.CodeArgumentError, nil, fmt.Sprintf("Extra inputs are not permitted: %s", field))
+ operationLog.Code = int(common.CodeArgumentError)
+ operationLog.Error = fmt.Errorf("extra inputs are not permitted: %s", field)
return
}
}
if parserConfig, ok := providedFields["parser_config"]; ok {
var config map[string]interface{}
if json.Unmarshal(parserConfig, &config) == nil {
- if _, ok := config["ext"]; ok {
+ if _, ok = config["ext"]; ok {
common.ResponseWithCodeData(c, common.CodeArgumentError, nil, "parser_config.ext is not supported; send parser configuration fields directly")
+ operationLog.Code = int(common.CodeArgumentError)
+ operationLog.Error = errors.New("parser_config.ext is not supported; send parser configuration fields directly")
return
}
}
@@ -486,10 +552,14 @@ func (h *DatasetsHandler) UpdateDataset(c *gin.Context) {
result, code, err := h.datasetsService.UpdateDataset(ctx, datasetID, userID, req)
if err != nil {
common.ErrorWithCode(c, code, err.Error())
+ operationLog.Code = int(code)
+ operationLog.Error = err
return
}
if code != common.CodeSuccess {
- common.ResponseWithCodeData(c, code, nil, "dataset updated failed")
+ common.ErrorWithCode(c, code, "dataset updated failed")
+ operationLog.Code = int(code)
+ operationLog.Error = errors.New("dataset updated failed")
return
}
@@ -697,21 +767,42 @@ func ingestionEventCursor(c *gin.Context, name string) (*int, bool) {
// DeleteDatasets handles DELETE /api/v1/datasets.
func (h *DatasetsHandler) DeleteDatasets(c *gin.Context) {
+ startAt := time.Now()
+ operationLog := &common.OperationLog{
+ EventTime: startAt,
+ Operation: "delete_dataset",
+ APIPath: c.FullPath(),
+ HTTPMethod: c.Request.Method,
+ IPAddress: c.ClientIP(),
+ }
+ defer func() {
+ operationLog.DurationMS = time.Since(startAt).Milliseconds()
+ common.Audit(operationLog)
+ }()
user, errorCode, errorMessage := GetUser(c)
if errorCode != common.CodeSuccess {
common.ErrorWithCode(c, errorCode, errorMessage)
+ operationLog.Code = int(errorCode)
+ operationLog.Error = errors.New(errorMessage)
return
}
+ operationLog.UserID = user.ID
- bodyBytes, rawPayload, ok := parseJSONRequestObject(c)
- if !ok {
+ bodyBytes, rawPayload, err := parseJSONRequestObject(c)
+ if err != nil {
+ common.ErrorWithCode(c, common.CodeArgumentError, err.Error())
+ operationLog.Code = int(common.CodeArgumentError)
+ operationLog.Error = err
return
}
// Mirror pydantic's extra="forbid" on DeleteDatasetReq.
for field := range rawPayload {
if field != "ids" && field != "delete_all" {
- common.ResponseWithCodeData(c, common.CodeArgumentError, nil, fmt.Sprintf("Extra inputs are not permitted: %s", field))
+ err = fmt.Errorf("extra inputs are not permitted: %s", field)
+ common.ErrorWithCode(c, common.CodeArgumentError, err.Error())
+ operationLog.Code = int(common.CodeArgumentError)
+ operationLog.Error = err
return
}
}
@@ -720,8 +811,10 @@ func (h *DatasetsHandler) DeleteDatasets(c *gin.Context) {
IDs *[]string `json:"ids"`
DeleteAll bool `json:"delete_all,omitempty"`
}
- if err := json.Unmarshal(bodyBytes, &req); err != nil {
- common.ResponseWithCodeData(c, common.CodeDataError, nil, err.Error())
+ if err = json.Unmarshal(bodyBytes, &req); err != nil {
+ common.ErrorWithCode(c, common.CodeDataError, err.Error())
+ operationLog.Code = int(common.CodeDataError)
+ operationLog.Error = err
return
}
@@ -736,7 +829,10 @@ func (h *DatasetsHandler) DeleteDatasets(c *gin.Context) {
}
}
if len(duplicates) > 0 {
- common.ResponseWithCodeData(c, common.CodeArgumentError, nil, fmt.Sprintf("Duplicate ids: '%s'", strings.Join(duplicates, ", ")))
+ err = fmt.Errorf("duplicate ids: '%s'", strings.Join(duplicates, ", "))
+ common.ErrorWithCode(c, common.CodeArgumentError, err.Error())
+ operationLog.Code = int(common.CodeArgumentError)
+ operationLog.Error = err
return
}
}
@@ -758,6 +854,8 @@ func (h *DatasetsHandler) DeleteDatasets(c *gin.Context) {
})
if err != nil {
common.ErrorWithCode(c, code, err.Error())
+ operationLog.Code = int(code)
+ operationLog.Error = err
return
}
diff --git a/internal/handler/dataset_list_test.go b/internal/handler/dataset_list_test.go
index eda0a1fa6f..986dfa0733 100644
--- a/internal/handler/dataset_list_test.go
+++ b/internal/handler/dataset_list_test.go
@@ -174,7 +174,7 @@ func TestDatasetsHandlerListDatasetsRejectsDuplicateIDs(t *testing.T) {
if body.Code != int(common.CodeArgumentError) {
t.Fatalf("code=%d want=%d", body.Code, common.CodeArgumentError)
}
- expected := fmt.Sprintf("Duplicate ids: '%s'", listDatasetsTestKBID)
+ expected := fmt.Sprintf("duplicate ids: '%s'", listDatasetsTestKBID)
if body.Message != expected {
t.Fatalf("message=%q want=%q", body.Message, expected)
}
diff --git a/internal/handler/document.go b/internal/handler/document.go
index 4d5068d6eb..623d425629 100644
--- a/internal/handler/document.go
+++ b/internal/handler/document.go
@@ -446,20 +446,40 @@ func (h *DocumentHandler) DeleteDocument(c *gin.Context) {
// DeleteDocuments handles DELETE /api/v1/datasets/:dataset_id/documents
func (h *DocumentHandler) DeleteDocuments(c *gin.Context) {
- _, errorCode, errorMessage := GetUser(c)
+ startAt := time.Now()
+ operationLog := &common.OperationLog{
+ EventTime: startAt,
+ Operation: "delete_dataset_documents",
+ APIPath: c.FullPath(),
+ HTTPMethod: c.Request.Method,
+ IPAddress: c.ClientIP(),
+ }
+ defer func() {
+ operationLog.DurationMS = time.Since(startAt).Milliseconds()
+ common.Audit(operationLog)
+ }()
+
+ user, errorCode, errorMessage := GetUser(c)
if errorCode != common.CodeSuccess {
common.ErrorWithCode(c, errorCode, errorMessage)
+ operationLog.Code = int(errorCode)
+ operationLog.Error = errors.New(errorMessage)
return
}
+ operationLog.UserID = user.ID
datasetID := c.Param("dataset_id")
if datasetID == "" {
common.ResponseWithCodeData(c, common.CodeArgumentError, nil, "dataset_id is required")
+ operationLog.Code = int(common.CodeArgumentError)
+ operationLog.Error = errors.New("dataset_id is required")
return
}
- bodyBytes, _, ok := parseJSONRequestObject(c)
- if !ok {
+ bodyBytes, _, err := parseJSONRequestObject(c)
+ if err != nil {
+ operationLog.Code = int(common.CodeArgumentError)
+ operationLog.Error = err
return
}
@@ -467,8 +487,10 @@ func (h *DocumentHandler) DeleteDocuments(c *gin.Context) {
IDs *[]string `json:"ids"`
DeleteAll bool `json:"delete_all,omitempty"`
}
- if err := json.Unmarshal(bodyBytes, &req); err != nil {
+ if err = json.Unmarshal(bodyBytes, &req); err != nil {
common.ResponseWithCodeData(c, common.CodeDataError, nil, err.Error())
+ operationLog.Code = int(common.CodeDataError)
+ operationLog.Error = err
return
}
@@ -483,7 +505,9 @@ func (h *DocumentHandler) DeleteDocuments(c *gin.Context) {
}
}
if len(duplicates) > 0 {
- common.ResponseWithCodeData(c, common.CodeArgumentError, nil, fmt.Sprintf("Field: <ids> - Message: <Duplicate ids: '%s'> - Value: <%s>", strings.Join(duplicates, ", "), string(bodyBytes)))
+ common.ResponseWithCodeData(c, common.CodeArgumentError, nil, fmt.Sprintf("field: <ids> - message: <duplicate ids: '%s'> - value: <%s>", strings.Join(duplicates, ", "), string(bodyBytes)))
+ operationLog.Code = int(common.CodeArgumentError)
+ operationLog.Error = fmt.Errorf("field: <ids> - message: <duplicate ids: '%s'> - value: <%s>", strings.Join(duplicates, ", "), string(bodyBytes))
return
}
}
@@ -494,21 +518,40 @@ func (h *DocumentHandler) DeleteDocuments(c *gin.Context) {
}
if len(ids) > 0 && req.DeleteAll {
common.ResponseWithCodeData(c, common.CodeDataError, nil, "should not provide both ids and delete_all")
+ operationLog.Code = int(common.CodeDataError)
+ operationLog.Error = errors.New("should not provide both ids and delete_all")
return
}
if len(ids) == 0 && !req.DeleteAll {
common.ResponseWithCodeData(c, common.CodeDataError, nil, "should either provide doc ids or set delete_all(true)")
+ operationLog.Code = int(common.CodeDataError)
+ operationLog.Error = errors.New("should either provide doc ids or set delete_all(true)")
return
}
+ operationLog.Resources = make(map[string]any)
+ if len(ids) > 0 {
+ operationLog.Resources = map[string]any{
+ "document_ids": ids,
+ }
+ }
+ if req.DeleteAll {
+ operationLog.Resources = map[string]any{
+ "delete_all": req.DeleteAll,
+ }
+ }
userID := c.GetString("user_id")
ctx := c.Request.Context()
deleted, err := h.documentService.DeleteDocuments(ctx, ids, req.DeleteAll, datasetID, userID)
if err != nil {
if respondPermissionErrorIf(c, err, false) {
+ operationLog.Code = int(common.CodePermissionError)
+ operationLog.Error = err
return
}
common.ResponseWithCodeData(c, common.CodeDataError, nil, err.Error())
+ operationLog.Code = int(common.CodeDataError)
+ operationLog.Error = err
return
}
@@ -1400,6 +1443,19 @@ type StartParseDocumentsRequest struct {
}
func (h *DocumentHandler) StartIngestionTask(c *gin.Context) {
+ startAt := time.Now()
+ operationLog := &common.OperationLog{
+ EventTime: startAt,
+ Operation: "start_ingestion_task",
+ APIPath: c.FullPath(),
+ HTTPMethod: c.Request.Method,
+ IPAddress: c.ClientIP(),
+ }
+ defer func() {
+ operationLog.DurationMS = time.Since(startAt).Milliseconds()
+ common.Audit(operationLog)
+ }()
+
datasetID := c.Param("dataset_id")
var req StartParseDocumentsRequest
@@ -1423,6 +1479,8 @@ func (h *DocumentHandler) StartIngestionTask(c *gin.Context) {
}
}
+ operationLog.UserID = userID
+
ctx := c.Request.Context()
if err := h.datasetService.CheckAccess(ctx, permission.Subject{UserID: userID}, datasetID, permission.OperationRun); err != nil {
respondPermissionError(c, err, false)
diff --git a/internal/handler/file.go b/internal/handler/file.go
index 19c05af749..05955c1d50 100644
--- a/internal/handler/file.go
+++ b/internal/handler/file.go
@@ -68,8 +68,6 @@ func NewFileHandler(fileService *file.FileService, userService *service.UserServ
// @Summary List Files
// @Description Get list of files under a folder with filtering, pagination and sorting (matches Python /files endpoint)
// @Tags file
-// @Accept json
-// @Produce json
// @Param parent_id query string false "parent folder ID (empty means root folder)"
// @Param tenant_id query string false "tenant whose files are listed (defaults to the current user)"
// @Param keywords query string false "search keywords (case-insensitive)"
@@ -122,12 +120,12 @@ func (h *FileHandler) ListFiles(c *gin.Context) {
}
}
- orderby := c.DefaultQuery("orderby", "create_time")
+ orderBy := c.DefaultQuery("orderby", "create_time")
desc := true
if descStr := c.Query("desc"); descStr != "" {
desc = descStr != "false"
}
- terms := orderTermsFromQuery(c, orderby, desc)
+ terms := orderTermsFromQuery(c, orderBy, desc)
ctx := c.Request.Context()
result, err := h.fileService.ListFilesForTenant(ctx, userID, tenantID, parentID, page, pageSize, terms, keywords)
@@ -143,8 +141,6 @@ func (h *FileHandler) ListFiles(c *gin.Context) {
// @Summary Get Parent Folder
// @Description Get parent folder of a file by file ID
// @Tags file
-// @Accept json
-// @Produce json
// @Param id path string true "file ID"
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/files/{id}/parent [get]
@@ -177,8 +173,6 @@ func (h *FileHandler) GetParentFolder(c *gin.Context) {
// @Summary Get File Ancestors
// @Description Get all ancestor folders in path from file to root
// @Tags file
-// @Accept json
-// @Produce json
// @Param id path string true "file ID"
// @Param tenant_id query string false "tenant the file belongs to"
// @Success 200 {object} map[string]interface{}
@@ -226,17 +220,16 @@ type CreateFolderRequest struct {
// @Description Upload files or create a folder based on content type
// @Tags file
// @Accept multipart/form-data, application/json
-// @Produce json
// @Param parent_id query string false "parent folder ID (for multipart/form-data)"
// @Param file formData file false "file to upload (for multipart/form-data)"
// @Success 200 {object} map[string]interface{}
// @Failure 400 {object} map[string]interface{}
-// @Router /v1/file/upload [post]
+// @Router /api/v1/files [POST]
func (h *FileHandler) UploadFile(c *gin.Context) {
startAt := time.Now()
operationLog := &common.OperationLog{
EventTime: startAt,
- Operation: "upload_file",
+ Operation: "upload_files_or_create_directory",
APIPath: c.FullPath(),
HTTPMethod: c.Request.Method,
IPAddress: c.ClientIP(),
@@ -253,13 +246,16 @@ func (h *FileHandler) UploadFile(c *gin.Context) {
operationLog.Error = errors.New(errorMessage)
return
}
+ operationLog.UserID = user.ID
userID := user.ID
contentType := c.ContentType()
ctx := c.Request.Context()
+ operationLog.Resources = make(map[string]any)
if strings.Contains(contentType, "multipart/form-data") {
+ operationLog.Operation = "upload_files"
uploadLimit := file.DeploymentUploadMaxBytes()
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, uploadLimit)
if cl := c.Request.ContentLength; cl > uploadLimit {
@@ -279,7 +275,7 @@ func (h *FileHandler) UploadFile(c *gin.Context) {
if form == nil {
common.ResponseWithCodeData(c, common.CodeBadRequest, nil, "No file part!")
operationLog.Code = int(common.CodeBadRequest)
- operationLog.Error = errors.New("no file part!")
+ operationLog.Error = errors.New("no file part")
return
}
var totalSize int64
@@ -322,6 +318,7 @@ func (h *FileHandler) UploadFile(c *gin.Context) {
operationLog.Error = errors.New("no file selected")
return
}
+ operationLog.Resources[fileHeader.Filename] = fileHeader.Size
}
result, err := h.fileService.UploadFile(ctx, userID, parentID, files, uploadLimit)
@@ -340,6 +337,7 @@ func (h *FileHandler) UploadFile(c *gin.Context) {
}
if strings.Contains(contentType, "application/json") {
+ operationLog.Operation = "create_directory"
var req CreateFolderRequest
if err := c.ShouldBindJSON(&req); err != nil {
common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, err.Error())
@@ -361,6 +359,7 @@ func (h *FileHandler) UploadFile(c *gin.Context) {
}
parentID = rootFolder["id"].(string)
}
+ operationLog.Resources["directory_name"] = req.Name
result, err := h.fileService.CreateFolder(ctx, userID, req.Name, parentID, req.Type)
if err != nil {
@@ -415,6 +414,7 @@ func (h *FileHandler) DeleteFiles(c *gin.Context) {
operationLog.Error = errors.New(errorMessage)
return
}
+ operationLog.UserID = user.ID
var req DeleteFileRequest
if err := c.ShouldBindJSON(&req); err != nil {
@@ -452,9 +452,6 @@ type MoveFileRequest struct {
// - both: move and rename simultaneously
//
// @Tags file
-// @Accept json
-// @Produce json
-// @Param body body MoveFileRequest true "Move file request"
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/files/move [post]
func (h *FileHandler) MoveFiles(c *gin.Context) {
@@ -478,6 +475,7 @@ func (h *FileHandler) MoveFiles(c *gin.Context) {
operationLog.Error = errors.New(errorMessage)
return
}
+ operationLog.UserID = user.ID
var req MoveFileRequest
if err := c.ShouldBindJSON(&req); err != nil {
@@ -521,7 +519,6 @@ func (h *FileHandler) MoveFiles(c *gin.Context) {
// @Summary Download File
// @Description Download a file by ID
// @Tags file
-// @Accept json
// @Produce octet-stream
// @Param file_id path string true "file ID"
// @Success 200 {file} binary "File stream"
@@ -546,7 +543,7 @@ func (h *FileHandler) Download(c *gin.Context) {
operationLog.Error = errors.New(errorMessage)
return
}
- userID := user.ID
+ operationLog.UserID = user.ID
fileID := c.Param("id")
if fileID == "" {
@@ -558,7 +555,7 @@ func (h *FileHandler) Download(c *gin.Context) {
ctx := c.Request.Context()
// Get file metadata and check permission
- fileContent, err := h.fileService.GetFileContent(ctx, userID, fileID)
+ fileContent, err := h.fileService.GetFileContent(ctx, user.ID, fileID)
if err != nil {
if respondPermissionErrorIf(c, err, true) {
operationLog.Code = int(common.CodePermissionError)
@@ -631,8 +628,6 @@ func (h *FileHandler) Download(c *gin.Context) {
// as needed. Folder inputs are expanded to their innermost files.
// The heavy DB work runs in a goroutine; the endpoint returns immediately.
// @Tags file
-// @Accept json
-// @Produce json
// @Param request body document.LinkToDatasetsRequest true "file_ids and kb_ids"
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/files/link-to-datasets [post]
@@ -657,11 +652,12 @@ func (h *FileHandler) LinkToDatasets(c *gin.Context) {
operationLog.Error = errors.New(errorMessage)
return
}
+ operationLog.UserID = user.ID
var req document.LinkToDatasetsRequest
// Tolerate bind errors: a malformed or empty body simply leaves the fields
// nil, which the validate_request-style check below reports as missing
- // arguments — matching Python's @validate_request behaviour and code.
+ // arguments — matching Python's @validate_request behavior and code.
_ = c.ShouldBindJSON(&req)
// Mirror Python @validate_request("file_ids", "kb_ids"): a key absent from
diff --git a/internal/handler/memory.go b/internal/handler/memory.go
index 2075c25f74..c7db153ce4 100644
--- a/internal/handler/memory.go
+++ b/internal/handler/memory.go
@@ -26,7 +26,6 @@ import (
"net/http"
"strconv"
"strings"
- "time"
"github.com/gin-gonic/gin"
@@ -83,22 +82,15 @@ func NewMemoryHandler(memoryService *service.MemoryService) *MemoryHandler {
// 3. Call service layer to create memory
// 4. Return creation result
func (h *MemoryHandler) CreateMemory(c *gin.Context) {
- quotaUser, ok := billingQuotaUser(c)
- if !ok {
+ user, errorCode, err := billingQuotaUser(c)
+ if err != nil {
+ common.ErrorWithCode(c, errorCode, err.Error())
return
}
- if !billingEnforceApps(c, quotaUser.ID) {
+ if !billingEnforceApps(c, user.ID) {
return
}
- // Check if API timing is enabled
- // If RAGFLOW_API_TIMING environment variable is set, request processing time will be logged
- timingEnabled := common.GetEnv(common.EnvRAGFlowAPITiming)
- var tStart time.Time
- if timingEnabled != "" {
- tStart = time.Now()
- }
-
// Get current logged-in user information
// GetUser is a context value set by the authentication middleware
user, errorCode, errorMessage := GetUser(c)
@@ -110,7 +102,7 @@ func (h *MemoryHandler) CreateMemory(c *gin.Context) {
// Parse JSON request body
var req service.CreateMemoryRequest
- if err := c.ShouldBindJSON(&req); err != nil {
+ if err = c.ShouldBindJSON(&req); err != nil {
common.ResponseWithCodeData(c, common.CodeBadRequest, nil, err.Error())
return
}
@@ -140,20 +132,11 @@ func (h *MemoryHandler) CreateMemory(c *gin.Context) {
}
// Record request parsing completion time (for timing)
- tParsed := time.Now()
ctx := c.Request.Context()
// Call service layer to create memory
result, err := h.memoryService.CreateMemory(ctx, userID, &req)
if err != nil {
- // Log error if timing is enabled
- if timingEnabled != "" {
- totalMs := float64(time.Since(tStart).Microseconds()) / 1000.0
- parseMs := float64(tParsed.Sub(tStart).Microseconds()) / 1000.0
- _ = parseMs
- _ = totalMs
- }
-
errMsg := err.Error()
// Determine if it's an argument error and return appropriate error code
if isArgumentError(errMsg) {
@@ -166,16 +149,6 @@ func (h *MemoryHandler) CreateMemory(c *gin.Context) {
return
}
- // Log success if timing is enabled
- if timingEnabled != "" {
- totalMs := float64(time.Since(tStart).Microseconds()) / 1000.0
- parseMs := float64(tParsed.Sub(tStart).Microseconds()) / 1000.0
- validateAndDbMs := totalMs - parseMs
- _ = parseMs
- _ = validateAndDbMs
- _ = totalMs
- }
-
// Return success response
common.SuccessWithData(c, result, "success")
}
diff --git a/internal/handler/search.go b/internal/handler/search.go
index 1a7057aaa0..3020eba3a9 100644
--- a/internal/handler/search.go
+++ b/internal/handler/search.go
@@ -160,30 +160,25 @@ type CreateSearchRequest struct {
}
func (h *SearchHandler) CreateSearch(c *gin.Context) {
- quotaUser, ok := billingQuotaUser(c)
- if !ok {
+ user, errorCode, err := billingQuotaUser(c)
+ if err != nil {
+ common.ErrorWithCode(c, errorCode, err.Error())
return
}
- if !billingEnforceApps(c, quotaUser.ID) {
+ if !billingEnforceApps(c, user.ID) {
return
}
- // Get current user from context (same as Python current_user)
- user, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.ErrorWithCode(c, errorCode, errorMessage)
- return
- }
userID := user.ID
// Parse request body (same as Python get_request_json())
var req CreateSearchRequest
- if err := c.ShouldBindJSON(&req); err != nil {
+ if err = c.ShouldBindJSON(&req); err != nil {
common.ResponseWithHttpCodeData(c, http.StatusInternalServerError, common.CodeBadRequest, nil, "Invalid request body: "+err.Error())
return
}
- if err := common.ValidateName(req.Name); err != nil {
+ if err = common.ValidateName(req.Name); err != nil {
common.ErrorWithCode(c, common.CodeDataError, err.Error())
return
}
diff --git a/internal/handler/stub.go b/internal/handler/stub.go
index feb9aed24d..b17bddb377 100644
--- a/internal/handler/stub.go
+++ b/internal/handler/stub.go
@@ -29,13 +29,12 @@ import (
)
// billingQuotaUser resolves the caller that the plan quota applies to.
-func billingQuotaUser(c *gin.Context) (*entity.User, bool) {
+func billingQuotaUser(c *gin.Context) (*entity.User, common.ErrorCode, error) {
user, code, message := GetUser(c)
if code != common.CodeSuccess {
- common.ErrorWithCode(c, code, message)
- return nil, false
+ return nil, code, errors.New(message)
}
- return user, true
+ return user, code, nil
}
// billingEnforceApps admits every new application: the community edition has
diff --git a/internal/handler/tenant.go b/internal/handler/tenant.go
index e04f257e0e..61432b6499 100644
--- a/internal/handler/tenant.go
+++ b/internal/handler/tenant.go
@@ -518,7 +518,6 @@ func (h *TenantHandler) AddTenantMember(c *gin.Context) {
return
}
operationLog.UserID = user.ID
- operationLog.UserName = user.Email
tenantID := c.Param("tenant_id")
if tenantID == "" {
@@ -598,7 +597,6 @@ func (h *TenantHandler) RemoveTenantMember(c *gin.Context) {
return
}
operationLog.UserID = user.ID
- operationLog.UserName = user.Email
tenantID := c.Param("tenant_id")
if tenantID == "" {
@@ -662,7 +660,6 @@ func (h *TenantHandler) AcceptTenantInvite(c *gin.Context) {
return
}
operationLog.UserID = user.ID
- operationLog.UserName = user.Email
tenantID := c.Param("tenant_id")
if tenantID == "" {
diff --git a/internal/handler/user.go b/internal/handler/user.go
index a60100abf9..c45874a59a 100644
--- a/internal/handler/user.go
+++ b/internal/handler/user.go
@@ -106,7 +106,6 @@ func (h *UserHandler) Register(c *gin.Context) {
return
}
operationLog.UserID = user.ID
- operationLog.UserName = user.Email
secretKey, err := server.GetSecretKey(ctx, kvrocks.Get())
if err != nil {
@@ -163,7 +162,8 @@ func (h *UserHandler) Login(c *gin.Context) {
operationLog.Error = err
return
}
- operationLog.UserName = req.Username
+ operationLog.Resources = make(map[string]any)
+ operationLog.Resources["user_name"] = req.Username
user, code, err := h.userService.Login(ctx, &req)
if err != nil {
@@ -233,7 +233,8 @@ func (h *UserHandler) LoginByEmail(c *gin.Context) {
operationLog.Error = err
return
}
- operationLog.UserName = req.Email
+ operationLog.Resources = make(map[string]any)
+ operationLog.Resources["user_name"] = req.Email
if !local.IsAdminAvailable() {
adminStatus := local.GetAdminStatus()
@@ -363,7 +364,6 @@ func (h *UserHandler) Logout(c *gin.Context) {
}
user := identity.User
operationLog.UserID = user.ID
- operationLog.UserName = user.Email
// Logout user
code, err = h.userService.Logout(ctx, user)
@@ -499,7 +499,6 @@ func (h *UserHandler) SetTenantInfo(c *gin.Context) {
return
}
operationLog.UserID = user.ID
- operationLog.UserName = user.Email
requiredKeys := []string{"tenant_id", "asr_id", "embd_id", "img2txt_id", "llm_id"}
missingArgumentMessage := "required argument are missing: tenant_id,asr_id,embd_id,img2txt_id,llm_id; "
diff --git a/internal/ingestion/service/ingestion_service.go b/internal/ingestion/service/ingestion_service.go
index 64b93cc575..fef61f75f6 100644
--- a/internal/ingestion/service/ingestion_service.go
+++ b/internal/ingestion/service/ingestion_service.go
@@ -359,7 +359,7 @@ func (e *Ingestor) consumeLoop() {
zap.Duration("handoff_duration", handoffDuration),
)
case <-e.dispatchCtx.Done():
- if err := handle.Nack(); err != nil {
+ if err = handle.Nack(); err != nil {
common.Error("nack task after shutdown interrupted handoff", err)
}
return
diff --git a/internal/service/file/file_delete.go b/internal/service/file/file_delete.go
index 622f579f2a..ca87ba2fb2 100644
--- a/internal/service/file/file_delete.go
+++ b/internal/service/file/file_delete.go
@@ -29,15 +29,15 @@ func (s *FileService) DeleteFiles(ctx context.Context, userID string, fileIDs []
for _, fileID := range fileIDs {
file, ok := filesByID[fileID]
if !ok {
- return errors.New("File or Folder not found!")
+ return errors.New("file or Folder not found")
}
if file.TenantID == "" {
- return errors.New("Tenant not found!")
+ return errors.New("tenant not found")
}
if file.ParentID == file.ID {
- return errors.New("Root folder cannot be deleted.")
+ return errors.New("root folder cannot be deleted")
}
- if err := s.checkFileTreeAccess(ctx, userID, file, permission.OperationDelete); err != nil {
+ if err = s.checkFileTreeAccess(ctx, userID, file, permission.OperationDelete); err != nil {
return err
}
}
@@ -48,11 +48,11 @@ func (s *FileService) DeleteFiles(ctx context.Context, userID string, fileIDs []
continue
}
if file.Type == FileTypeFolder {
- if err := s.deleteFolderRecursive(ctx, file); err != nil {
- return fmt.Errorf("Failed to delete folder: %w", err)
+ if err = s.deleteFolderRecursive(ctx, file); err != nil {
+ return fmt.Errorf("failed to delete folder: %w", err)
}
- } else if err := s.deleteSingleFile(ctx, file); err != nil {
- return fmt.Errorf("Failed to delete file: %w", err)
+ } else if err = s.deleteSingleFile(ctx, file); err != nil {
+ return fmt.Errorf("failed to delete file: %w", err)
}
}
return nil
diff --git a/internal/service/file/file_folder.go b/internal/service/file/file_folder.go
index 61800e170a..bdbc61752e 100644
--- a/internal/service/file/file_folder.go
+++ b/internal/service/file/file_folder.go
@@ -21,7 +21,7 @@ func (s *FileService) GetRootFolder(ctx context.Context, tenantID string) (map[s
if err != nil {
return nil, err
}
- if err := checkFileAccess(ctx, tenantID, file, permission.OperationRead); err != nil {
+ if err = checkFileAccess(ctx, tenantID, file, permission.OperationRead); err != nil {
return nil, err
}
return s.toFileResponse(file), nil
@@ -448,14 +448,14 @@ func (s *FileService) CreateFolder(ctx context.Context, userID, name, parentID,
if err != nil {
return nil, err
}
- if err := permission.NewDatabaseChecker(dao.DB).CheckFeature(ctx, permission.Subject{UserID: userID}, "file", permission.ActionWrite); err != nil {
+ if err = permission.NewDatabaseChecker(dao.DB).CheckFeature(ctx, permission.Subject{UserID: userID}, "file", permission.ActionWrite); err != nil {
return nil, err
}
// "/" is the root folder name and the path separator used by recursive
// folder creation, so names containing it collide with the root folder
// and break path-based lookups.
if strings.Contains(name, "/") {
- return nil, errors.New(`Folder name cannot contain "/"`)
+ return nil, errors.New(`folder name cannot contain "/"`)
}
if parentID == "" {
@@ -473,7 +473,7 @@ func (s *FileService) CreateFolder(ctx context.Context, userID, name, parentID,
if parentFolder.TenantID != tenantID {
return nil, permission.ErrResourceNotFound
}
- if err := checkFileAccess(ctx, userID, parentFolder, permission.OperationCreate); err != nil {
+ if err = checkFileAccess(ctx, userID, parentFolder, permission.OperationCreate); err != nil {
return nil, err
}
diff --git a/test/testcases/test_sdk_api/test_dataset_mangement/test_delete_datasets.py b/test/testcases/test_sdk_api/test_dataset_mangement/test_delete_datasets.py
index 6031b37784..31b3a55f96 100644
--- a/test/testcases/test_sdk_api/test_dataset_mangement/test_delete_datasets.py
+++ b/test/testcases/test_sdk_api/test_dataset_mangement/test_delete_datasets.py
@@ -106,7 +106,7 @@ class TestDatasetsDelete:
@pytest.mark.p2
def test_ids_duplicate(self, client, add_datasets_func):
ids = [dataset.id for dataset in add_datasets_func]
- with pytest.raises(Exception, match="Duplicate ids:"):
+ with pytest.raises(Exception, match="duplicate ids:"):
client.delete_datasets(ids=ids + ids)
assert {dataset.id for dataset in client.list_datasets()} == set(ids)
diff --git a/test/testcases/test_sdk_api/test_dataset_mangement/test_list_datasets.py b/test/testcases/test_sdk_api/test_dataset_mangement/test_list_datasets.py
index 87587312de..7b1ce138e7 100644
--- a/test/testcases/test_sdk_api/test_dataset_mangement/test_list_datasets.py
+++ b/test/testcases/test_sdk_api/test_dataset_mangement/test_list_datasets.py
@@ -265,5 +265,5 @@ class TestDatasetsList:
@pytest.mark.p2
def test_ids_duplicates(self, client, add_datasets):
dataset_id = add_datasets[0].id
- with pytest.raises(Exception, match="Duplicate ids:"):
+ with pytest.raises(Exception, match="duplicate ids:"):
client.list_datasets(ids=[dataset_id, dataset_id])
diff --git a/test/testcases/test_sdk_api/test_file_management_within_dataset/test_delete_documents.py b/test/testcases/test_sdk_api/test_file_management_within_dataset/test_delete_documents.py
index 3e4ef84714..08bea35d00 100644
--- a/test/testcases/test_sdk_api/test_file_management_within_dataset/test_delete_documents.py
+++ b/test/testcases/test_sdk_api/test_file_management_within_dataset/test_delete_documents.py
@@ -93,7 +93,7 @@ class TestDocumentsDeletion:
document_ids = [document.id for document in documents]
with pytest.raises(Exception) as exception_info:
dataset.delete_documents(ids=document_ids + document_ids)
- assert "Field: <ids> - Message: <Duplicate ids:" in str(exception_info.value), str(exception_info.value)
+ assert "field: <ids> - message: <duplicate ids:" in str(exception_info.value), str(exception_info.value)
assert {doc.id for doc in dataset.list_documents()} == set(document_ids)