Skip to content

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

Go: add context, part14 (#17446)

Jin Hai7f21a7ba189c
diff --git a/api/apps/restful_apis/chat_api.py b/api/apps/restful_apis/chat_api.py
index 456df204ea..74f5114fb3 100644
--- a/api/apps/restful_apis/chat_api.py
+++ b/api/apps/restful_apis/chat_api.py
@@ -509,7 +509,7 @@ async def get_chat(chat_id):
else:
return get_json_result(
data=False,
- message="No authorization.",
+ message="no authorization",
code=RetCode.AUTHENTICATION_ERROR,
)
@@ -525,7 +525,7 @@ async def get_chat(chat_id):
@login_required
async def update_chat(chat_id):
if not await _ensure_owned_chat(chat_id):
- return get_json_result(data=False, message="No authorization.", code=RetCode.AUTHENTICATION_ERROR)
+ return get_json_result(data=False, message="no authorization", code=RetCode.AUTHENTICATION_ERROR)
try:
req = await get_request_json()
@@ -607,7 +607,7 @@ async def update_chat(chat_id):
@login_required
async def patch_chat(chat_id):
if not await _ensure_owned_chat(chat_id):
- return get_json_result(data=False, message="No authorization.", code=RetCode.AUTHENTICATION_ERROR)
+ return get_json_result(data=False, message="no authorization", code=RetCode.AUTHENTICATION_ERROR)
try:
req = await get_request_json()
@@ -695,7 +695,7 @@ async def patch_chat(chat_id):
@login_required
async def delete_chat(chat_id):
if not await _ensure_owned_chat(chat_id):
- return get_json_result(data=False, message="No authorization.", code=RetCode.AUTHENTICATION_ERROR)
+ return get_json_result(data=False, message="no authorization", code=RetCode.AUTHENTICATION_ERROR)
try:
if not DialogService.update_by_id(chat_id, {"status": StatusEnum.INVALID.value}):
@@ -757,7 +757,7 @@ async def bulk_delete_chats():
async def create_session(chat_id):
"""Create a new conversation session for the given chat, owned by the authenticated user."""
if not await _ensure_owned_chat(chat_id):
- return get_json_result(data=False, message="No authorization.", code=RetCode.AUTHENTICATION_ERROR)
+ return get_json_result(data=False, message="no authorization", code=RetCode.AUTHENTICATION_ERROR)
try:
req = await get_request_json()
ok, dia = DialogService.get_by_id(chat_id)
@@ -765,7 +765,7 @@ async def create_session(chat_id):
return get_data_error_result(message="Chat not found!")
name = req.get("name", "New session")
if not isinstance(name, str) or not name.strip():
- return get_data_error_result(message="`name` can not be empty.")
+ return get_data_error_result(message="`name` can not be empty")
name = name.strip()[:255]
conv = {
"id": get_uuid(),
@@ -791,7 +791,7 @@ async def list_sessions(chat_id):
if not await _ensure_owned_chat(chat_id):
return get_json_result(
data=False,
- message="No authorization.",
+ message="no authorization",
code=RetCode.AUTHENTICATION_ERROR,
)
page_number = int(request.args.get("page", 1))
@@ -813,7 +813,7 @@ async def list_sessions(chat_id):
@login_required
async def get_session(chat_id, session_id):
if not await _ensure_owned_chat(chat_id):
- return get_json_result(data=False, message="No authorization.", code=RetCode.AUTHENTICATION_ERROR)
+ return get_json_result(data=False, message="no authorization", code=RetCode.AUTHENTICATION_ERROR)
try:
ok, conv = await thread_pool_exec(ConversationService.get_by_id, session_id)
if not ok:
@@ -837,19 +837,19 @@ async def get_session(chat_id, session_id):
@login_required
async def update_session(chat_id, session_id):
if not await _ensure_owned_chat(chat_id):
- return get_json_result(data=False, message="No authorization.", code=RetCode.AUTHENTICATION_ERROR)
+ return get_json_result(data=False, message="no authorization", code=RetCode.AUTHENTICATION_ERROR)
try:
req = await get_request_json()
if not ConversationService.query(id=session_id, dialog_id=chat_id):
return get_data_error_result(message="Session not found!")
if "message" in req or "messages" in req:
- return get_data_error_result(message="`messages` cannot be changed.")
+ return get_data_error_result(message="`messages` cannot be changed")
if "reference" in req:
- return get_data_error_result(message="`reference` cannot be changed.")
+ return get_data_error_result(message="`reference` cannot be changed")
name = req.get("name")
if name is not None:
if not isinstance(name, str) or not name.strip():
- return get_data_error_result(message="`name` can not be empty.")
+ return get_data_error_result(message="`name` can not be empty")
req["name"] = name.strip()[:255]
update_fields = {k: v for k, v in req.items() if k not in {"id", "dialog_id", "chat_id", "user_id"}}
if not ConversationService.update_by_id(session_id, update_fields):
@@ -866,7 +866,7 @@ async def update_session(chat_id, session_id):
@login_required
async def delete_sessions(chat_id):
if not await _ensure_owned_chat(chat_id):
- return get_json_result(data=False, message="No authorization.", code=RetCode.AUTHENTICATION_ERROR)
+ return get_json_result(data=False, message="no authorization", code=RetCode.AUTHENTICATION_ERROR)
try:
req = await get_request_json()
if not req:
@@ -917,7 +917,7 @@ async def delete_sessions(chat_id):
@login_required
async def delete_session_message(chat_id, session_id, msg_id):
if not await _ensure_owned_chat(chat_id):
- return get_json_result(data=False, message="No authorization.", code=RetCode.AUTHENTICATION_ERROR)
+ return get_json_result(data=False, message="no authorization", code=RetCode.AUTHENTICATION_ERROR)
try:
ok, conv = ConversationService.get_by_id(session_id)
if not ok or conv.dialog_id != chat_id:
@@ -943,7 +943,7 @@ async def delete_session_message(chat_id, session_id, msg_id):
async def update_message_feedback(chat_id, session_id, msg_id):
owned = await _ensure_owned_chat(chat_id)
if not owned:
- return get_json_result(data=False, message="No authorization.", code=RetCode.AUTHENTICATION_ERROR)
+ return get_json_result(data=False, message="no authorization", code=RetCode.AUTHENTICATION_ERROR)
try:
req = await get_request_json()
ok, conv = ConversationService.get_by_id(session_id)
@@ -1179,7 +1179,7 @@ async def session_completion(chat_id_in_arg=""):
if not await _ensure_owned_chat(chat_id):
return get_json_result(
data=False,
- message="No authorization.",
+ message="no authorization",
code=RetCode.AUTHENTICATION_ERROR,
)
e, dia = await thread_pool_exec(DialogService.get_by_id, chat_id)
diff --git a/api/apps/restful_apis/chat_channel_api.py b/api/apps/restful_apis/chat_channel_api.py
index 0ba9cc5f99..83c6425c95 100644
--- a/api/apps/restful_apis/chat_channel_api.py
+++ b/api/apps/restful_apis/chat_channel_api.py
@@ -28,7 +28,7 @@ LOGGER = logging.getLogger(__name__)
def _chat_channel_auth_error(channel_id: str, user_id: str):
"""Return the chat channel authorization failure response and log the denial."""
LOGGER.warning("chat channel access denied: channel_id=%s user_id=%s", channel_id, user_id)
- return get_json_result(data=False, message="No authorization.", code=RetCode.AUTHENTICATION_ERROR)
+ return get_json_result(data=False, message="no authorization", code=RetCode.AUTHENTICATION_ERROR)
@manager.route("/chat-channels", methods=["POST"]) # noqa: F821
diff --git a/api/apps/restful_apis/connector_api.py b/api/apps/restful_apis/connector_api.py
index 8348351bd7..1e54a306bb 100644
--- a/api/apps/restful_apis/connector_api.py
+++ b/api/apps/restful_apis/connector_api.py
@@ -43,7 +43,7 @@ LOGGER = logging.getLogger(__name__)
def _connector_auth_error(connector_id: str, user_id: str):
"""Return the connector authorization failure response and log the denial."""
LOGGER.warning("connector access denied: connector_id=%s user_id=%s", connector_id, user_id)
- return get_json_result(data=False, message="No authorization.", code=RetCode.AUTHENTICATION_ERROR)
+ return get_json_result(data=False, message="no authorization", code=RetCode.AUTHENTICATION_ERROR)
@manager.route("/connectors/<connector_id>", methods=["PATCH"]) # noqa: F821
diff --git a/api/apps/restful_apis/dataset_api.py b/api/apps/restful_apis/dataset_api.py
index 7027796596..732d3df4f2 100644
--- a/api/apps/restful_apis/dataset_api.py
+++ b/api/apps/restful_apis/dataset_api.py
@@ -780,7 +780,7 @@ def delete_dataset_structure(tenant_id, dataset_id):
)
if success:
return get_result(data=result)
- if result == "No authorization.":
+ if result == "no authorization":
return get_result(data=False, message=result, code=RetCode.AUTHENTICATION_ERROR)
return get_error_data_result(message=result)
except Exception as e:
diff --git a/api/apps/restful_apis/dify_retrieval_api.py b/api/apps/restful_apis/dify_retrieval_api.py
index 782b0f5459..c4eb214ecb 100644
--- a/api/apps/restful_apis/dify_retrieval_api.py
+++ b/api/apps/restful_apis/dify_retrieval_api.py
@@ -260,7 +260,7 @@ async def retrieval(tenant_id):
tenant_id,
kb_id,
)
- return build_error_result(message="No authorization.", code=RetCode.AUTHENTICATION_ERROR)
+ return build_error_result(message="no authorization", code=RetCode.AUTHENTICATION_ERROR)
model_config = resolve_model_config(kb.tenant_id, LLMType.EMBEDDING, kb.embd_id)
embd_mdl = LLMBundle(kb.tenant_id, model_config)
if metadata_condition:
diff --git a/api/apps/restful_apis/document_api.py b/api/apps/restful_apis/document_api.py
index 0aaca3ca40..4642ce2a57 100644
--- a/api/apps/restful_apis/document_api.py
+++ b/api/apps/restful_apis/document_api.py
@@ -215,7 +215,7 @@ async def update_document(tenant_id, dataset_id, document_id):
# Verify ownership and existence of dataset and document
if not KnowledgebaseService.query(id=dataset_id, tenant_id=tenant_id):
- return get_error_data_result(message="You don't own the dataset.")
+ return get_error_data_result(message="you don't own the dataset")
e, kb = KnowledgebaseService.get_by_id(dataset_id)
if not e:
return get_error_data_result(message="Can't find this dataset!")
@@ -223,7 +223,7 @@ async def update_document(tenant_id, dataset_id, document_id):
# Prepare data for validation
docs = DocumentService.query(kb_id=dataset_id, id=document_id)
if not docs:
- return get_error_data_result(message="The dataset doesn't own the document.")
+ return get_error_data_result(message="the dataset doesn't own the document")
# Validate document update request parameters
try:
@@ -484,8 +484,8 @@ async def upload_document(dataset_id, tenant_id):
return get_error_data_result(message=f"Can't find the dataset with ID {dataset_id}!", code=RetCode.DATA_ERROR)
if not check_kb_team_permission(kb, tenant_id):
- logging.error("No authorization.")
- return get_error_data_result(message="No authorization.", code=RetCode.AUTHENTICATION_ERROR)
+ logging.error("no authorization")
+ return get_error_data_result(message="no authorization", code=RetCode.AUTHENTICATION_ERROR)
if upload_type == "web":
return await _upload_web_document(dataset_id, kb, tenant_id)
@@ -1216,12 +1216,12 @@ async def update_metadata_config(tenant_id, dataset_id, document_id):
"""
# Verify ownership and existence of dataset
if not KnowledgebaseService.query(id=dataset_id, tenant_id=tenant_id):
- return get_error_data_result(message="You don't own the dataset.")
+ return get_error_data_result(message="you don't own the dataset")
# Verify document exists in the dataset
doc = DocumentService.query(id=document_id, kb_id=dataset_id)
if not doc:
- msg = f"Document {document_id} not found in dataset {dataset_id}"
+ msg = f"document {document_id} not found in dataset {dataset_id}"
return get_error_data_result(message=msg)
doc = doc[0]
@@ -1434,7 +1434,7 @@ async def ingest(tenant_id):
def _run_sync(user_id: str, req):
for doc_id in req["doc_ids"]:
if not DocumentService.accessible(doc_id, user_id):
- return RetCode.AUTHENTICATION_ERROR, "No authorization."
+ return RetCode.AUTHENTICATION_ERROR, "no authorization"
kb_table_num_map = {}
for doc_id in req["doc_ids"]:
@@ -1969,7 +1969,7 @@ async def batch_update_document_status(tenant_id, dataset_id):
# Verify dataset ownership
if not KnowledgebaseService.query(id=dataset_id, tenant_id=tenant_id):
- return get_error_data_result(message="You don't own the dataset.")
+ return get_error_data_result(message="you don't own the dataset")
e, kb = KnowledgebaseService.get_by_id(dataset_id)
if not e:
diff --git a/api/apps/restful_apis/file2document_api.py b/api/apps/restful_apis/file2document_api.py
index 5161705810..baf8bdfeb3 100644
--- a/api/apps/restful_apis/file2document_api.py
+++ b/api/apps/restful_apis/file2document_api.py
@@ -167,7 +167,7 @@ async def convert():
file_ids,
kb_ids,
)
- return get_data_error_result(message="No authorization.")
+ return get_data_error_result(message="no authorization")
for kb_id, kb in kb_map.items():
if not check_kb_team_permission(kb, user_id):
@@ -178,7 +178,7 @@ async def convert():
file_ids,
kb_ids,
)
- return get_data_error_result(message="No authorization.")
+ return get_data_error_result(message="no authorization")
# Run the blocking DB work in a thread so the event loop is not blocked.
# For large folders this prevents 504 Gateway Timeout by returning as
diff --git a/api/apps/restful_apis/search_api.py b/api/apps/restful_apis/search_api.py
index 3323f971f1..9cc9c8dd7d 100644
--- a/api/apps/restful_apis/search_api.py
+++ b/api/apps/restful_apis/search_api.py
@@ -136,7 +136,7 @@ async def update(search_id):
return get_data_error_result(message="Authorized identity.")
if not SearchService.accessible4deletion(search_id, current_user.id):
- return get_json_result(data=False, message="No authorization.", code=RetCode.AUTHENTICATION_ERROR)
+ return get_json_result(data=False, message="no authorization", code=RetCode.AUTHENTICATION_ERROR)
try:
search_app = SearchService.query(tenant_id=current_user.id, id=search_id)[0]
@@ -181,7 +181,7 @@ async def update(search_id):
@login_required
def delete_search(search_id):
if not SearchService.accessible4deletion(search_id, current_user.id):
- return get_json_result(data=False, message="No authorization.", code=RetCode.AUTHENTICATION_ERROR)
+ return get_json_result(data=False, message="no authorization", code=RetCode.AUTHENTICATION_ERROR)
try:
if not SearchService.delete_by_id(search_id):
@@ -199,7 +199,7 @@ async def completion(search_id):
if not SearchService.accessible4deletion(search_id, current_user.id):
return get_json_result(
data=False,
- message="No authorization.",
+ message="no authorization",
code=RetCode.AUTHENTICATION_ERROR,
)
diff --git a/api/apps/restful_apis/tenant_api.py b/api/apps/restful_apis/tenant_api.py
index a0a69a3f4d..04b2e6e1a1 100644
--- a/api/apps/restful_apis/tenant_api.py
+++ b/api/apps/restful_apis/tenant_api.py
@@ -44,7 +44,7 @@ def user_list(tenant_id):
if current_user.id != tenant_id:
return get_json_result(
data=False,
- message="No authorization.",
+ message="no authorization",
code=RetCode.AUTHENTICATION_ERROR,
)
@@ -64,7 +64,7 @@ async def create(tenant_id):
if current_user.id != tenant_id:
return get_json_result(
data=False,
- message="No authorization.",
+ message="no authorization",
code=RetCode.AUTHENTICATION_ERROR,
)
@@ -141,7 +141,7 @@ async def rm(tenant_id):
if current_user.id != tenant_id and current_user.id != user_id:
return get_json_result(
data=False,
- message="No authorization.",
+ message="no authorization",
code=RetCode.AUTHENTICATION_ERROR,
)
diff --git a/api/apps/services/dataset_api_service.py b/api/apps/services/dataset_api_service.py
index 91de0a583c..4fa4682e75 100644
--- a/api/apps/services/dataset_api_service.py
+++ b/api/apps/services/dataset_api_service.py
@@ -474,7 +474,7 @@ async def get_knowledge_graph(dataset_id: str, tenant_id: str):
:return: (success, result) or (success, error_message)
"""
if not KnowledgebaseService.accessible(dataset_id, tenant_id):
- return False, "No authorization."
+ return False, "no authorization"
_, kb = KnowledgebaseService.get_by_id(dataset_id)
req = {"kb_id": [dataset_id], "knowledge_graph_kwd": ["graph"]}
@@ -515,7 +515,7 @@ def delete_knowledge_graph(dataset_id: str, tenant_id: str):
:return: (success, result) or (success, error_message)
"""
if not KnowledgebaseService.accessible(dataset_id, tenant_id):
- return False, "No authorization."
+ return False, "no authorization"
_, kb = KnowledgebaseService.get_by_id(dataset_id)
from rag.nlp import search
from rag.graphrag.phase_markers import clear_phase_markers
@@ -547,7 +547,7 @@ def run_index(dataset_id: str, tenant_id: str, index_type: str):
if not dataset_id:
return False, 'Lack of "Dataset ID"'
if not KnowledgebaseService.accessible(dataset_id, tenant_id):
- return False, "No authorization."
+ return False, "no authorization"
ok, kb = KnowledgebaseService.get_by_id(dataset_id)
if not ok:
@@ -607,7 +607,7 @@ def trace_index(dataset_id: str, tenant_id: str, index_type: str):
return False, 'Lack of "Dataset ID"'
if not KnowledgebaseService.accessible(dataset_id, tenant_id):
- return False, "No authorization."
+ return False, "no authorization"
ok, kb = KnowledgebaseService.get_by_id(dataset_id)
if not ok:
@@ -637,7 +637,7 @@ def list_tags(dataset_id: str, tenant_id: str):
return False, 'Lack of "Dataset ID"'
if not KnowledgebaseService.accessible(dataset_id, tenant_id):
- return False, "No authorization."
+ return False, "no authorization"
tenants = UserTenantService.get_tenants_by_user_id(tenant_id)
tags = []
@@ -747,7 +747,7 @@ def delete_tags(dataset_id: str, tenant_id: str, tags: list[str]):
return False, 'Lack of "Dataset ID"'
if not KnowledgebaseService.accessible(dataset_id, tenant_id):
- return False, "No authorization."
+ return False, "no authorization"
ok, kb = KnowledgebaseService.get_by_id(dataset_id)
if not ok:
@@ -794,7 +794,7 @@ def list_ingestion_logs(
return False, 'Lack of "Dataset ID"'
if not KnowledgebaseService.accessible(dataset_id, tenant_id):
- return False, "No authorization."
+ return False, "no authorization"
from api.db.services.pipeline_operation_log_service import PipelineOperationLogService
@@ -837,7 +837,7 @@ def get_ingestion_log(dataset_id: str, tenant_id: str, log_id: str):
return False, 'Lack of "Dataset ID"'
if not KnowledgebaseService.accessible(dataset_id, tenant_id):
- return False, "No authorization."
+ return False, "no authorization"
from api.db.services.pipeline_operation_log_service import PipelineOperationLogService
@@ -878,7 +878,7 @@ def delete_index(dataset_id: str, tenant_id: str, index_type: str, wipe: bool =
return False, 'Lack of "Dataset ID"'
if not KnowledgebaseService.accessible(dataset_id, tenant_id):
- return False, "No authorization."
+ return False, "no authorization"
ok, kb = KnowledgebaseService.get_by_id(dataset_id)
if not ok:
@@ -947,7 +947,7 @@ def rename_tag(dataset_id: str, tenant_id: str, from_tag: str, to_tag: str):
return False, 'Lack of "Dataset ID"'
if not KnowledgebaseService.accessible(dataset_id, tenant_id):
- return False, "No authorization."
+ return False, "no authorization"
ok, kb = KnowledgebaseService.get_by_id(dataset_id)
if not ok:
@@ -1253,7 +1253,7 @@ def check_embedding(dataset_id: str, tenant_id: str, req: dict):
return False, 'Lack of "Dataset ID"'
if not KnowledgebaseService.accessible(dataset_id, tenant_id):
- return False, "No authorization."
+ return False, "no authorization"
ok, kb = KnowledgebaseService.get_by_id(dataset_id)
if not ok:
@@ -1675,7 +1675,7 @@ async def has_any_wiki(dataset_id: str, tenant_id: str):
auth failure. Runs a ``limit=1`` search and reads only the total.
"""
if not KnowledgebaseService.accessible(dataset_id, tenant_id):
- return False, "No authorization."
+ return False, "no authorization"
_, kb = KnowledgebaseService.get_by_id(dataset_id)
pack = _wiki_index_or_none(kb.tenant_id, dataset_id)
@@ -1765,7 +1765,7 @@ async def get_dataset_structure(dataset_id: str, tenant_id: str, kind: str, keyw
``(False, message)`` on auth/validation failure.
"""
if not KnowledgebaseService.accessible(dataset_id, tenant_id):
- return False, "No authorization."
+ return False, "no authorization"
resolved_kind = _resolve_dataset_structure_kind(kind)
if not resolved_kind:
@@ -1966,7 +1966,7 @@ async def get_dataset_structure(dataset_id: str, tenant_id: str, kind: str, keyw
async def get_wiki_alteration(dataset_id: str, tenant_id: str):
"""Return doc-level drift between current dataset docs and compiled wiki provenance."""
if not KnowledgebaseService.accessible(dataset_id, tenant_id):
- return False, "No authorization."
+ return False, "no authorization"
ok, kb = KnowledgebaseService.get_by_id(dataset_id)
if not ok:
return False, "Invalid Dataset ID"
@@ -2075,7 +2075,7 @@ async def list_wiki_pages(
pages of the same type grouped together visually.
"""
if not KnowledgebaseService.accessible(dataset_id, tenant_id):
- return False, "No authorization."
+ return False, "no authorization"
_, kb = KnowledgebaseService.get_by_id(dataset_id)
pack = _wiki_index_or_none(kb.tenant_id, dataset_id)
@@ -2160,7 +2160,7 @@ async def list_wiki_topics(
):
"""List wiki topics for the dataset Artifact tab."""
if not KnowledgebaseService.accessible(dataset_id, tenant_id):
- return False, "No authorization."
+ return False, "no authorization"
_, kb = KnowledgebaseService.get_by_id(dataset_id)
pack = _wiki_index_or_none(kb.tenant_id, dataset_id)
@@ -2261,7 +2261,7 @@ async def get_wiki_page(
Returns ``(True, page_dict)`` or ``(True, None)`` when no row matches.
"""
if not KnowledgebaseService.accessible(dataset_id, tenant_id):
- return False, "No authorization."
+ return False, "no authorization"
_, kb = KnowledgebaseService.get_by_id(dataset_id)
pack = _wiki_index_or_none(kb.tenant_id, dataset_id)
@@ -2335,7 +2335,7 @@ async def get_wiki_page(
async def has_any_skill(dataset_id: str, tenant_id: str):
"""Fast existence probe for the dataset Skills sidebar entry."""
if not KnowledgebaseService.accessible(dataset_id, tenant_id):
- return False, "No authorization."
+ return False, "no authorization"
_, kb = KnowledgebaseService.get_by_id(dataset_id)
pack = _skill_index_or_none(kb.tenant_id, dataset_id)
@@ -2368,7 +2368,7 @@ async def has_any_skill(dataset_id: str, tenant_id: str):
async def get_skill_tree(dataset_id: str, tenant_id: str):
"""Fetch the one-shot recursive skill tree for this dataset."""
if not KnowledgebaseService.accessible(dataset_id, tenant_id):
- return False, "No authorization."
+ return False, "no authorization"
_, kb = KnowledgebaseService.get_by_id(dataset_id)
pack = _skill_index_or_none(kb.tenant_id, dataset_id)
@@ -2416,7 +2416,7 @@ async def delete_skills(dataset_id: str, tenant_id: str):
not exist yet there is nothing to delete, so it succeeds with ``0``.
"""
if not KnowledgebaseService.accessible(dataset_id, tenant_id):
- return False, "No authorization."
+ return False, "no authorization"
_, kb = KnowledgebaseService.get_by_id(dataset_id)
pack = _skill_index_or_none(kb.tenant_id, dataset_id)
@@ -2452,7 +2452,7 @@ async def delete_skill(dataset_id: str, tenant_id: str, skill_kwd: str):
left untouched. Returns ``(True, {"deleted": <n>})``.
"""
if not KnowledgebaseService.accessible(dataset_id, tenant_id):
- return False, "No authorization."
+ return False, "no authorization"
_, kb = KnowledgebaseService.get_by_id(dataset_id)
pack = _skill_index_or_none(kb.tenant_id, dataset_id)
@@ -2476,7 +2476,7 @@ async def delete_skill(dataset_id: str, tenant_id: str, skill_kwd: str):
async def get_skill_page(dataset_id: str, tenant_id: str, skill_kwd: str):
"""Fetch the full markdown body for a single skill node."""
if not KnowledgebaseService.accessible(dataset_id, tenant_id):
- return False, "No authorization."
+ return False, "no authorization"
_, kb = KnowledgebaseService.get_by_id(dataset_id)
pack = _skill_index_or_none(kb.tenant_id, dataset_id)
@@ -2585,7 +2585,7 @@ def _nav_item(row: dict) -> dict:
async def _nav_search(dataset_id: str, tenant_id: str, condition: dict, page: int, page_size: int):
"""Run one nav-tree search and shape the hits into UI nodes."""
if not KnowledgebaseService.accessible(dataset_id, tenant_id):
- return False, "No authorization."
+ return False, "no authorization"
_, kb = KnowledgebaseService.get_by_id(dataset_id)
pack = _compiled_index_or_none(kb.tenant_id, dataset_id)
@@ -2660,7 +2660,7 @@ async def delete_nav(dataset_id: str, tenant_id: str):
index yet.
"""
if not KnowledgebaseService.accessible(dataset_id, tenant_id):
- return False, "No authorization."
+ return False, "no authorization"
_, kb = KnowledgebaseService.get_by_id(dataset_id)
pack = _compiled_index_or_none(kb.tenant_id, dataset_id)
@@ -2694,7 +2694,7 @@ async def delete_nav_node(dataset_id: str, tenant_id: str, name: str):
name = name.strip()
if not KnowledgebaseService.accessible(dataset_id, tenant_id):
- return False, "No authorization."
+ return False, "no authorization"
_, kb = KnowledgebaseService.get_by_id(dataset_id)
pack = _compiled_index_or_none(kb.tenant_id, dataset_id)
@@ -2831,7 +2831,7 @@ async def update_wiki_page(
``(False, message)`` on authorization failure.
"""
if not KnowledgebaseService.accessible(dataset_id, tenant_id):
- return False, "No authorization."
+ return False, "no authorization"
_, kb = KnowledgebaseService.get_by_id(dataset_id)
pack = _wiki_index_or_none(kb.tenant_id, dataset_id)
@@ -3190,7 +3190,7 @@ async def get_wiki_graph(
``(False, message)`` on authorization failure.
"""
if not KnowledgebaseService.accessible(dataset_id, tenant_id):
- return False, "No authorization."
+ return False, "no authorization"
_, kb = KnowledgebaseService.get_by_id(dataset_id)
empty = {"entities": [], "relations": []}
@@ -3443,7 +3443,7 @@ async def clear_wiki(dataset_id: str, tenant_id: str):
``(False, str)`` on auth failure.
"""
if not KnowledgebaseService.accessible(dataset_id, tenant_id):
- return False, "No authorization."
+ return False, "no authorization"
_, kb = KnowledgebaseService.get_by_id(dataset_id)
pack = _wiki_index_or_none(kb.tenant_id, dataset_id)
diff --git a/api/apps/services/file_api_service.py b/api/apps/services/file_api_service.py
index 00f1a6355d..f0d870ffac 100644
--- a/api/apps/services/file_api_service.py
+++ b/api/apps/services/file_api_service.py
@@ -185,7 +185,7 @@ def get_parent_folder(file_id: str, user_id: str = None):
# Permission check
if user_id and not check_file_team_permission(file, user_id):
- return False, "No authorization."
+ return False, "no authorization"
parent_folder = FileService.get_parent_folder(file_id)
return True, {"parent_folder": parent_folder.to_json()}
@@ -207,7 +207,7 @@ def get_all_parent_folders(file_id: str, user_id: str = None):
# Permission check
if user_id and not check_file_team_permission(file, user_id):
- return False, "No authorization."
+ return False, "no authorization"
parent_folders = FileService.get_all_parent_folders(file_id)
return True, {"parent_folders": [pf.to_json() for pf in parent_folders]}
@@ -479,7 +479,7 @@ async def move_files(uid: str, src_file_ids: list, dest_file_id: str = None, new
if not file.tenant_id:
return False, "Tenant not found!"
if not check_file_team_permission(file, uid):
- return False, "No authorization."
+ return False, "no authorization"
dest_folder = None
if dest_file_id:
@@ -603,5 +603,5 @@ def get_file_content(uid: str, file_id: str):
if not e:
return False, "Document not found!"
if not check_file_team_permission(file, uid):
- return False, "No authorization."
+ return False, "no authorization"
return True, file
diff --git a/api/db/services/conversation_service.py b/api/db/services/conversation_service.py
index 274aae0833..5487901a04 100644
--- a/api/db/services/conversation_service.py
+++ b/api/db/services/conversation_service.py
@@ -230,7 +230,7 @@ def structure_answer(conv, ans, message_id, session_id):
async def async_completion(tenant_id, chat_id, question, name="New session", session_id=None, stream=True, **kwargs):
- assert name, "`name` can not be empty."
+ assert name, "`name` can not be empty"
dia = DialogService.query(id=chat_id, tenant_id=tenant_id, status=StatusEnum.VALID.value)
assert dia, "You do not own the chat."
diff --git a/api/db/services/knowledgebase_service.py b/api/db/services/knowledgebase_service.py
index e28fcbafbc..491786baad 100644
--- a/api/db/services/knowledgebase_service.py
+++ b/api/db/services/knowledgebase_service.py
@@ -427,7 +427,7 @@ class KnowledgebaseService(CommonService):
return False, get_data_error_result(message="Dataset name must be string.")
dataset_name = name.strip()
if dataset_name == "":
- return False, get_data_error_result(message="Dataset name can't be empty.")
+ return False, get_data_error_result(message="dataset name can't be empty")
if len(dataset_name.encode("utf-8")) > DATASET_NAME_LIMIT:
return False, get_data_error_result(message=f"Dataset name length is {len(dataset_name)} which is large than {DATASET_NAME_LIMIT}")
diff --git a/api/utils/validation_utils.py b/api/utils/validation_utils.py
index e6a16f3a89..20847b6f4f 100644
--- a/api/utils/validation_utils.py
+++ b/api/utils/validation_utils.py
@@ -572,7 +572,7 @@ class CreateDatasetReq(Base):
Raises:
PydanticCustomError: For structural errors in these cases:
- Missing MIME prefix header
- - Invalid MIME prefix format
+ - invalid MIME prefix format
- Unsupported image MIME type
Example:
@@ -591,7 +591,7 @@ class CreateDatasetReq(Base):
if "," in v:
prefix, _ = v.split(",", 1)
if not prefix.startswith("data:"):
- raise PydanticCustomError("format_invalid", "Invalid MIME prefix format. Must start with 'data:'")
+ raise PydanticCustomError("format_invalid", "invalid MIME prefix format. Must start with 'data:'")
mime_type = prefix[5:].split(";")[0]
supported_mime_types = ["image/jpeg", "image/png"]
@@ -600,7 +600,7 @@ class CreateDatasetReq(Base):
return v
else:
- raise PydanticCustomError("format_invalid", "Missing MIME prefix. Expected format: data:<mime>;base64,<data>")
+ raise PydanticCustomError("format_invalid", "missing MIME prefix. Expected format: data:<mime>;base64,<data>")
@field_validator("embedding_model", mode="before")
@classmethod
@@ -646,11 +646,11 @@ class CreateDatasetReq(Base):
return v
if "@" not in v:
- raise PydanticCustomError("format_invalid", "Embedding model identifier must follow <model_name>@<provider> format")
+ raise PydanticCustomError("format_invalid", "embedding model identifier must follow <model_name>@<provider> format")
components = v.split("@", 1)
if len(components) != 2 or not all(components):
- raise PydanticCustomError("format_invalid", "Both model_name and provider must be non-empty strings")
+ raise PydanticCustomError("format_invalid", "both model_name and provider must be non-empty strings")
model_name, provider = components
if not model_name.strip() or not provider.strip():
diff --git a/docs/references/http_api_reference.md b/docs/references/http_api_reference.md
index 365544895c..1469945941 100644
--- a/docs/references/http_api_reference.md
+++ b/docs/references/http_api_reference.md
@@ -3314,7 +3314,7 @@ Failure:
```json
{
"code": 102,
- "message": "No authorization."
+ "message": "no authorization"
}
```
@@ -3371,7 +3371,7 @@ Failure:
```json
{
"code": 102,
- "message": "No authorization."
+ "message": "no authorization"
}
```
@@ -3419,7 +3419,7 @@ Failure:
```json
{
"code": 102,
- "message": "No authorization."
+ "message": "no authorization"
}
```
@@ -8517,7 +8517,7 @@ Failure:
```json
{
"code": 109,
- "message": "No authorization."
+ "message": "no authorization"
}
```
@@ -8565,7 +8565,7 @@ Failure:
```json
{
"code": 109,
- "message": "No authorization."
+ "message": "no authorization"
}
```
@@ -8624,6 +8624,6 @@ Failure:
```json
{
"code": 109,
- "message": "No authorization."
+ "message": "no authorization"
}
```
diff --git a/internal/admin/handler.go b/internal/admin/handler.go
index 2c9904fccd..a63a4d0876 100644
--- a/internal/admin/handler.go
+++ b/internal/admin/handler.go
@@ -144,7 +144,8 @@ func (h *Handler) Logout(c *gin.Context) {
return
}
- if err := h.service.Logout(user); err != nil {
+ ctx := c.Request.Context()
+ if err := h.service.Logout(ctx, user); err != nil {
common.ErrorWithCode(c, common.CodeServerError, err.Error())
return
}
@@ -217,8 +218,8 @@ func (h *Handler) ListUsers(c *gin.Context) {
var users []map[string]interface{}
switch common.GetRAGFlowType() {
case common.OpenSourceVersion:
-
- users, err = h.service.ListUsers(pageInt, pageSizeInt, name, status, sort, orderBy)
+ ctx := c.Request.Context()
+ users, err = h.service.ListUsers(ctx, pageInt, pageSizeInt, name, status, sort, orderBy)
if err != nil {
common.ErrorWithCode(c, common.CodeServerError, err.Error())
return
@@ -337,12 +338,13 @@ func (h *Handler) ChangePassword(c *gin.Context) {
}
var req ChangePasswordHTTPRequest
- if err := c.ShouldBindJSON(&req); err != nil {
+ if err = c.ShouldBindJSON(&req); err != nil {
common.ErrorWithCode(c, common.CodeBadRequest, "New password is required")
return
}
- if err := h.service.ChangePassword(username, req.NewPassword); err != nil {
+ ctx := c.Request.Context()
+ if err = h.service.ChangePassword(ctx, username, req.NewPassword); err != nil {
common.ErrorWithCode(c, common.CodeServerError, err.Error())
return
}
@@ -363,7 +365,7 @@ func (h *Handler) UpdateUserActivateStatus(c *gin.Context) {
}
var req UpdateActivateStatusHTTPRequest
- if err := c.ShouldBindJSON(&req); err != nil {
+ if err = c.ShouldBindJSON(&req); err != nil {
common.ErrorWithCode(c, common.CodeBadRequest, "Activation status is required")
return
}
@@ -374,7 +376,8 @@ func (h *Handler) UpdateUserActivateStatus(c *gin.Context) {
}
isActive := req.ActivateStatus == "on"
- if err := h.service.UpdateUserActivateStatus(username, isActive); err != nil {
+ ctx := c.Request.Context()
+ if err = h.service.UpdateUserActivateStatus(ctx, username, isActive); err != nil {
common.ErrorWithCode(c, common.CodeServerError, err.Error())
return
}
@@ -396,7 +399,8 @@ func (h *Handler) GrantAdmin(c *gin.Context) {
return
}
- if err := h.service.GrantAdmin(username); err != nil {
+ ctx := c.Request.Context()
+ if err = h.service.GrantAdmin(ctx, username); err != nil {
common.ErrorWithCode(c, common.CodeServerError, err.Error())
return
}
@@ -418,7 +422,8 @@ func (h *Handler) RevokeAdmin(c *gin.Context) {
return
}
- if err = h.service.RevokeAdmin(username); err != nil {
+ ctx := c.Request.Context()
+ if err = h.service.RevokeAdmin(ctx, username); err != nil {
common.ErrorWithCode(c, common.CodeServerError, err.Error())
return
}
diff --git a/internal/admin/handler_ee.go b/internal/admin/handler_ee.go
index 3b880c3ed3..6198e0738d 100644
--- a/internal/admin/handler_ee.go
+++ b/internal/admin/handler_ee.go
@@ -1635,7 +1635,9 @@ func (h *Handler) GenerateUserAPIKey(c *gin.Context) {
return
}
- apiKey, err := h.service.GenerateUserAPIKey(username)
+ ctx := c.Request.Context()
+
+ apiKey, err := h.service.GenerateUserAPIKey(ctx, username)
if err != nil {
common.ErrorWithCode(c, common.CodeServerError, err.Error())
return
@@ -1658,7 +1660,9 @@ func (h *Handler) DeleteUserAPIKey(c *gin.Context) {
return
}
- result, err := h.service.DeleteUserAPIKey(username, key)
+ ctx := c.Request.Context()
+
+ result, err := h.service.DeleteUserAPIKey(ctx, username, key)
if err != nil {
common.ErrorWithCode(c, common.CodeServerError, err.Error())
return
@@ -1674,7 +1678,9 @@ func (h *Handler) ListUserAPIKeys(c *gin.Context) {
return
}
- result, err := h.service.ListUserAPIKeys(username)
+ ctx := c.Request.Context()
+
+ result, err := h.service.ListUserAPIKeys(ctx, username)
if err != nil {
common.ErrorWithCode(c, common.CodeServerError, err.Error())
return
diff --git a/internal/admin/service.go b/internal/admin/service.go
index 325408b59a..3e321a9ed7 100644
--- a/internal/admin/service.go
+++ b/internal/admin/service.go
@@ -94,11 +94,11 @@ func NewService() *Service {
}
// Logout user logout
-func (s *Service) Logout(user interface{}) error {
+func (s *Service) Logout(ctx context.Context, user interface{}) error {
// Invalidate token by setting it to INVALID_ prefix
if u, ok := user.(*entity.User); ok {
invalidToken := "INVALID_" + generateRandomHex(16)
- return s.userDAO.UpdateAccessToken(u, invalidToken)
+ return s.userDAO.UpdateAccessToken(ctx, dao.DB, u, invalidToken)
}
return nil
}
@@ -117,8 +117,8 @@ func (s *Service) StopIngestionTasks(ctx context.Context, tasks []string) ([]*en
}
// GetUserByToken get user by access token
-func (s *Service) GetUserByToken(token string) (*entity.User, error) {
- user, err := s.userDAO.GetByAccessToken(token)
+func (s *Service) GetUserByToken(ctx context.Context, token string) (*entity.User, error) {
+ user, err := s.userDAO.GetByAccessToken(ctx, dao.DB, token)
if err != nil {
return nil, common.ErrInvalidToken
}
@@ -142,8 +142,8 @@ func generateRandomHex(n int) string {
}
// ListUsers list all users
-func (s *Service) ListUsers(pageIndex, pageSize int, name, status, sort, orderBy string) ([]map[string]interface{}, error) {
- users, _, err := s.userDAO.List(pageIndex*pageSize, pageSize, name, status, sort, orderBy)
+func (s *Service) ListUsers(ctx context.Context, pageIndex, pageSize int, name, status, sort, orderBy string) ([]map[string]interface{}, error) {
+ users, _, err := s.userDAO.List(ctx, dao.DB, pageIndex*pageSize, pageSize, name, status, sort, orderBy)
if err != nil {
return nil, err
}
@@ -176,7 +176,7 @@ func (s *Service) CreateUser(ctx context.Context, username, password, role strin
return nil, fmt.Errorf("invalid email address: %s", username)
}
- existUser, _ := s.userDAO.GetByEmail(username)
+ existUser, _ := s.userDAO.GetByEmail(ctx, dao.DB, username)
if existUser != nil {
return nil, fmt.Errorf("user '%s' already exists", username)
}
@@ -225,7 +225,7 @@ func (s *Service) CreateUser(ctx context.Context, username, password, role strin
}
// 1. Create user
- if err := tx.Create(user).Error; err != nil {
+ if err = tx.Create(user).Error; err != nil {
rollbackTx()
return nil, fmt.Errorf("failed to create user: %w", err)
}
@@ -279,7 +279,7 @@ func (s *Service) CreateUser(ctx context.Context, username, password, role strin
InvitedBy: userID,
Status: &userTenantStatus,
}
- if err := tx.Create(userTenant).Error; err != nil {
+ if err = tx.Create(userTenant).Error; err != nil {
rollbackTx()
return nil, fmt.Errorf("failed to create user-tenant relation: %w", err)
}
@@ -290,7 +290,7 @@ func (s *Service) CreateUser(ctx context.Context, username, password, role strin
common.Warn("failed to get init tenant LLM configs", zap.Error(err))
// Continue without LLM configs - not a critical error
} else if len(tenantLLMs) > 0 {
- if err := tx.Create(&tenantLLMs).Error; err != nil {
+ if err = tx.Create(&tenantLLMs).Error; err != nil {
common.Warn("failed to create tenant LLM configs", zap.Error(err))
// Continue without LLM configs - not a critical error
}
@@ -309,13 +309,13 @@ func (s *Service) CreateUser(ctx context.Context, username, password, role strin
Size: 0,
Location: &fileLocation,
}
- if err := tx.Create(file).Error; err != nil {
+ if err = tx.Create(file).Error; err != nil {
rollbackTx()
return nil, fmt.Errorf("failed to create root file folder: %w", err)
}
// Commit transaction
- if err := tx.Commit().Error; err != nil {
+ if err = tx.Commit().Error; err != nil {
return nil, fmt.Errorf("failed to commit transaction: %w", err)
}
@@ -499,7 +499,7 @@ func (s *Service) DeleteUser(ctx context.Context, username string) (*DeleteUserR
Username: username,
DeletedDetails: []string{fmt.Sprintf("Drop user: %s", username)},
}
- userList, err := s.userDAO.ListByEmail(username)
+ userList, err := s.userDAO.ListByEmail(ctx, dao.DB, username)
if err != nil || len(userList) == 0 {
return nil, fmt.Errorf("user '%s' not found", username)
}
@@ -521,7 +521,7 @@ func (s *Service) DeleteUser(ctx context.Context, username string) (*DeleteUserR
}
// Get user-tenant relations
- tenants, err := s.userTenantDAO.GetByUserIDAll(user.ID)
+ tenants, err := s.userTenantDAO.GetByUserIDAll(ctx, dao.DB, user.ID)
if err != nil {
common.Warn("failed to get user-tenant relations", zap.Error(err))
}
@@ -690,8 +690,8 @@ func (s *Service) DeleteUser(ctx context.Context, username string) (*DeleteUserR
//
// Returns:
// - error: error message
-func (s *Service) ChangePassword(username, newPassword string) error {
- userList, err := s.userDAO.ListByEmail(username)
+func (s *Service) ChangePassword(ctx context.Context, username, newPassword string) error {
+ userList, err := s.userDAO.ListByEmail(ctx, dao.DB, username)
if err != nil || len(userList) == 0 {
return fmt.Errorf("user '%s' not found", username)
}
@@ -718,7 +718,7 @@ func (s *Service) ChangePassword(username, newPassword string) error {
user.Password = &hashedPassword
- if err := s.userDAO.Update(user); err != nil {
+ if err = s.userDAO.Update(ctx, dao.DB, user); err != nil {
return fmt.Errorf("failed to update user: %w", err)
}
@@ -732,8 +732,8 @@ func (s *Service) ChangePassword(username, newPassword string) error {
//
// Returns:
// - error: error message
-func (s *Service) UpdateUserActivateStatus(username string, isActive bool) error {
- userList, err := s.userDAO.ListByEmail(username)
+func (s *Service) UpdateUserActivateStatus(ctx context.Context, username string, isActive bool) error {
+ userList, err := s.userDAO.ListByEmail(ctx, dao.DB, username)
if err != nil || len(userList) == 0 {
return fmt.Errorf("user '%s' not found", username)
}
@@ -755,7 +755,7 @@ func (s *Service) UpdateUserActivateStatus(username string, isActive bool) error
user.IsActive = targetStatus
- if err := s.userDAO.Update(user); err != nil {
+ if err = s.userDAO.Update(ctx, dao.DB, user); err != nil {
return fmt.Errorf("failed to update user: %w", err)
}
@@ -768,8 +768,8 @@ func (s *Service) UpdateUserActivateStatus(username string, isActive bool) error
//
// Returns:
// - error: error message
-func (s *Service) GrantAdmin(username string) error {
- userList, err := s.userDAO.ListByEmail(username)
+func (s *Service) GrantAdmin(ctx context.Context, username string) error {
+ userList, err := s.userDAO.ListByEmail(ctx, dao.DB, username)
if err != nil || len(userList) == 0 {
return fmt.Errorf("user '%s' not found", username)
}
@@ -787,7 +787,7 @@ func (s *Service) GrantAdmin(username string) error {
isSuperuser := true
user.IsSuperuser = &isSuperuser
- if err := s.userDAO.Update(user); err != nil {
+ if err = s.userDAO.Update(ctx, dao.DB, user); err != nil {
return fmt.Errorf("failed to update user: %w", err)
}
@@ -800,8 +800,8 @@ func (s *Service) GrantAdmin(username string) error {
//
// Returns:
// - error: error message
-func (s *Service) RevokeAdmin(username string) error {
- userList, err := s.userDAO.ListByEmail(username)
+func (s *Service) RevokeAdmin(ctx context.Context, username string) error {
+ userList, err := s.userDAO.ListByEmail(ctx, dao.DB, username)
if err != nil || len(userList) == 0 {
return fmt.Errorf("user '%s' not found", username)
}
@@ -819,7 +819,7 @@ func (s *Service) RevokeAdmin(username string) error {
isSuperuser := false
user.IsSuperuser = &isSuperuser
- if err = s.userDAO.Update(user); err != nil {
+ if err = s.userDAO.Update(ctx, dao.DB, user); err != nil {
return fmt.Errorf("failed to update user: %w", err)
}
@@ -843,13 +843,13 @@ func (s *Service) GetUserAgents(username string) ([]map[string]interface{}, erro
// ListUserAPITokens get user API keys
func (s *Service) ListUserAPITokens(ctx context.Context, username string) ([]map[string]interface{}, error) {
// 1. Get user details
- user, err := s.userDAO.GetByEmail(username)
+ user, err := s.userDAO.GetByEmail(ctx, dao.DB, username)
if err != nil {
return nil, fmt.Errorf("user not found: %w", err)
}
// 2. Get user's tenants
- userTenants, err := s.userTenantDAO.GetByUserID(user.ID)
+ userTenants, err := s.userTenantDAO.GetByUserID(ctx, dao.DB, user.ID)
if err != nil || len(userTenants) == 0 {
return nil, fmt.Errorf("tenant not found")
}
@@ -884,13 +884,13 @@ func (s *Service) ListUserAPITokens(ctx context.Context, username string) ([]map
// GenerateUserAPIToken generate API key for user
func (s *Service) GenerateUserAPIToken(ctx context.Context, username string) (map[string]interface{}, error) {
// 1. Get user details
- user, err := s.userDAO.GetByEmail(username)
+ user, err := s.userDAO.GetByEmail(ctx, dao.DB, username)
if err != nil {
return nil, fmt.Errorf("user not found: %w", err)
}
// 2. Get user's tenants
- userTenants, err := s.userTenantDAO.GetByUserID(user.ID)
+ userTenants, err := s.userTenantDAO.GetByUserID(ctx, dao.DB, user.ID)
if err != nil || len(userTenants) == 0 {
return nil, fmt.Errorf("tenant not found")
}
@@ -926,13 +926,13 @@ func (s *Service) GenerateUserAPIToken(ctx context.Context, username string) (ma
// DeleteUserAPIToken delete user API key
func (s *Service) DeleteUserAPIToken(ctx context.Context, username, key string) error {
// 1. Get user details
- user, err := s.userDAO.GetByEmail(username)
+ user, err := s.userDAO.GetByEmail(ctx, dao.DB, username)
if err != nil {
return fmt.Errorf("user not found: %w", err)
}
// 2. Get user's tenants
- userTenants, err := s.userTenantDAO.GetByUserID(user.ID)
+ userTenants, err := s.userTenantDAO.GetByUserID(ctx, dao.DB, user.ID)
if err != nil || len(userTenants) == 0 {
return fmt.Errorf("tenant not found")
}
@@ -1697,11 +1697,11 @@ func (s *Service) InitDefaultAdmin() error {
IsSuperuser: &isSuperuser,
}
- if err := dao.DB.Create(user).Error; err != nil {
+ if err = dao.DB.Create(user).Error; err != nil {
return fmt.Errorf("can't init admin: %w", err)
}
- if err := s.addTenantForAdmin(userID, defaultNickname); err != nil {
+ if err = s.addTenantForAdmin(userID, defaultNickname); err != nil {
return fmt.Errorf("failed to add tenant for admin: %w", err)
}
@@ -1725,7 +1725,7 @@ func (s *Service) InitDefaultAdmin() error {
if user.Nickname != "" {
nickname = user.Nickname
}
- if err := s.addTenantForAdmin(user.ID, nickname); err != nil {
+ if err = s.addTenantForAdmin(user.ID, nickname); err != nil {
return err
}
}
diff --git a/internal/admin/service_ee.go b/internal/admin/service_ee.go
index 9dff7ade52..4313cb8d68 100644
--- a/internal/admin/service_ee.go
+++ b/internal/admin/service_ee.go
@@ -17,6 +17,7 @@
package admin
import (
+ "context"
"errors"
"fmt"
"mime/multipart"
@@ -1061,9 +1062,9 @@ func (s *Service) PurgeUsersData(preview bool, days int, userPlan *string, userA
}
// GenerateUserAPIKey create tenant API key for tenant
-func (s *Service) GenerateUserAPIKey(username string) (map[string]interface{}, error) {
+func (s *Service) GenerateUserAPIKey(ctx context.Context, username string) (map[string]interface{}, error) {
- user, err := s.userDAO.GetByEmail(username)
+ user, err := s.userDAO.GetByEmail(ctx, dao.DB, username)
if err != nil {
return nil, fmt.Errorf("user not found: %w", err)
}
@@ -1079,9 +1080,9 @@ func (s *Service) GenerateUserAPIKey(username string) (map[string]interface{}, e
}
// DeleteUserAPIKey delete user API key
-func (s *Service) DeleteUserAPIKey(username, key string) (map[string]interface{}, error) {
+func (s *Service) DeleteUserAPIKey(ctx context.Context, username, key string) (map[string]interface{}, error) {
- user, err := s.userDAO.GetByEmail(username)
+ user, err := s.userDAO.GetByEmail(ctx, dao.DB, username)
if err != nil {
return nil, fmt.Errorf("user not found: %w", err)
}
@@ -1098,9 +1099,9 @@ func (s *Service) DeleteUserAPIKey(username, key string) (map[string]interface{}
}
// ListUserAPIKeys list user API keys
-func (s *Service) ListUserAPIKeys(username string) ([]map[string]interface{}, error) {
+func (s *Service) ListUserAPIKeys(ctx context.Context, username string) ([]map[string]interface{}, error) {
- user, err := s.userDAO.GetByEmail(username)
+ user, err := s.userDAO.GetByEmail(ctx, dao.DB, username)
if err != nil {
return nil, fmt.Errorf("user not found: %w", err)
}
diff --git a/internal/dao/memory.go b/internal/dao/memory.go
index cad03e4bcb..8b64d935aa 100644
--- a/internal/dao/memory.go
+++ b/internal/dao/memory.go
@@ -132,7 +132,7 @@ func (dao *MemoryDAO) GetByID(ctx context.Context, db *gorm.DB, id string) (*ent
// GetByIDWithContext retrieves a memory record by ID from database with context.
func (dao *MemoryDAO) GetByIDWithContext(ctx context.Context, db *gorm.DB, id string) (*entity.Memory, error) {
var memory entity.Memory
- err := db.WithContext(ctx).WithContext(ctx).Where("id = ?", id).First(&memory).Error
+ err := db.WithContext(ctx).Where("id = ?", id).First(&memory).Error
if err != nil {
return nil, err
}
diff --git a/internal/dao/user.go b/internal/dao/user.go
index 2aedbc50b3..94d38ff71a 100644
--- a/internal/dao/user.go
+++ b/internal/dao/user.go
@@ -20,6 +20,8 @@ import (
"context"
"ragflow/internal/entity"
+
+ "gorm.io/gorm"
)
// UserDAO user data access object
@@ -30,24 +32,24 @@ func NewUserDAO() *UserDAO {
return &UserDAO{}
}
-// Create create user
-func (dao *UserDAO) Create(user *entity.User) error {
- return DB.Create(user).Error
+// Create user
+func (dao *UserDAO) Create(ctx context.Context, db *gorm.DB, user *entity.User) error {
+ return db.WithContext(ctx).Create(user).Error
}
// GetByID get user by ID
-func (dao *UserDAO) GetByID(ctx context.Context, id uint) (*entity.User, error) {
+func (dao *UserDAO) GetByID(ctx context.Context, db *gorm.DB, id uint) (*entity.User, error) {
var user entity.User
- err := DB.First(&user, id).Error
+ err := db.WithContext(ctx).First(&user, id).Error
if err != nil {
return nil, err
}
return &user, nil
}
-func (dao *UserDAO) GetByTenantID(tenantID string) (*entity.User, error) {
+func (dao *UserDAO) GetByTenantID(ctx context.Context, db *gorm.DB, tenantID string) (*entity.User, error) {
var user entity.User
- err := DB.Where("id = ?", tenantID).First(&user).Error
+ err := db.WithContext(ctx).Where("id = ?", tenantID).First(&user).Error
if err != nil {
return nil, err
}
@@ -55,9 +57,9 @@ func (dao *UserDAO) GetByTenantID(tenantID string) (*entity.User, error) {
}
// GetNicknameByID returns a user's nickname by string id.
-func (dao *UserDAO) GetNicknameByID(ctx context.Context, id string) (string, error) {
+func (dao *UserDAO) GetNicknameByID(ctx context.Context, db *gorm.DB, id string) (string, error) {
var nickname string
- err := DB.WithContext(ctx).
+ err := db.WithContext(ctx).
Model(&entity.User{}).
Where("id = ?", id).
Select("nickname").
@@ -66,9 +68,9 @@ func (dao *UserDAO) GetNicknameByID(ctx context.Context, id string) (string, err
}
// GetByEmail get user by email
-func (dao *UserDAO) GetByEmail(email string) (*entity.User, error) {
+func (dao *UserDAO) GetByEmail(ctx context.Context, db *gorm.DB, email string) (*entity.User, error) {
var user entity.User
- query := DB.Where("email = ?", email)
+ query := db.WithContext(ctx).Where("email = ?", email)
err := query.First(&user).Error
if err != nil {
return nil, err
@@ -77,9 +79,9 @@ func (dao *UserDAO) GetByEmail(email string) (*entity.User, error) {
}
// GetByAccessToken get user by access token
-func (dao *UserDAO) GetByAccessToken(token string) (*entity.User, error) {
+func (dao *UserDAO) GetByAccessToken(ctx context.Context, db *gorm.DB, token string) (*entity.User, error) {
var user entity.User
- err := DB.Where("access_token = ?", token).First(&user).Error
+ err := db.WithContext(ctx).Where("access_token = ?", token).First(&user).Error
if err != nil {
return nil, err
}
@@ -87,26 +89,26 @@ func (dao *UserDAO) GetByAccessToken(token string) (*entity.User, error) {
}
// Update update user
-func (dao *UserDAO) Update(user *entity.User) error {
- return DB.Save(user).Error
+func (dao *UserDAO) Update(ctx context.Context, db *gorm.DB, user *entity.User) error {
+ return db.WithContext(ctx).Save(user).Error
}
// UpdateAccessToken update user's access token
-func (dao *UserDAO) UpdateAccessToken(user *entity.User, token string) error {
- return DB.Model(user).Update("access_token", token).Error
+func (dao *UserDAO) UpdateAccessToken(ctx context.Context, db *gorm.DB, user *entity.User, token string) error {
+ return db.WithContext(ctx).Model(user).Update("access_token", token).Error
}
-// List list users (only active users with status != "0")
-func (dao *UserDAO) List(offset, limit int, name, status, sort, orderBy string) ([]*entity.User, int64, error) {
+// List users (only active users with status != "0")
+func (dao *UserDAO) List(ctx context.Context, db *gorm.DB, offset, limit int, name, status, sort, orderBy string) ([]*entity.User, int64, error) {
var users []*entity.User
var total int64
// Only count users with status != "0" (not deleted)
- if err := DB.Model(&entity.User{}).Count(&total).Error; err != nil {
+ if err := db.WithContext(ctx).Model(&entity.User{}).Count(&total).Error; err != nil {
return nil, 0, err
}
- query := DB.Model(&entity.User{})
+ query := db.WithContext(ctx).Model(&entity.User{})
if offset > 0 {
query = query.Offset(offset)
}
@@ -118,24 +120,24 @@ func (dao *UserDAO) List(offset, limit int, name, status, sort, orderBy string)
}
// Delete delete user
-func (dao *UserDAO) Delete(id uint) error {
- return DB.Delete(&entity.User{}, id).Error
+func (dao *UserDAO) Delete(ctx context.Context, db *gorm.DB, id uint) error {
+ return db.WithContext(ctx).Delete(&entity.User{}, id).Error
}
// DeleteByID delete user by string ID (soft delete - set status to 0)
-func (dao *UserDAO) DeleteByID(id string) error {
- return DB.Model(&entity.User{}).Where("id = ?", id).Update("status", "0").Error
+func (dao *UserDAO) DeleteByID(ctx context.Context, db *gorm.DB, id string) error {
+ return db.WithContext(ctx).Model(&entity.User{}).Where("id = ?", id).Update("status", "0").Error
}
// HardDelete hard delete user by string ID
-func (dao *UserDAO) HardDelete(id string) error {
- return DB.Unscoped().Where("id = ?", id).Delete(&entity.User{}).Error
+func (dao *UserDAO) HardDelete(ctx context.Context, db *gorm.DB, id string) error {
+ return db.WithContext(ctx).Unscoped().Where("id = ?", id).Delete(&entity.User{}).Error
}
// ListByEmail list users by email (only active users with status != "0")
// Returns all users matching the given email address
-func (dao *UserDAO) ListByEmail(email string) ([]*entity.User, error) {
+func (dao *UserDAO) ListByEmail(ctx context.Context, db *gorm.DB, email string) ([]*entity.User, error) {
var users []*entity.User
- err := DB.Where("email = ?", email).Find(&users).Error
+ err := db.WithContext(ctx).Where("email = ?", email).Find(&users).Error
return users, err
}
diff --git a/internal/dao/user_canvas.go b/internal/dao/user_canvas.go
index 451c0aca0d..0a1873b02c 100644
--- a/internal/dao/user_canvas.go
+++ b/internal/dao/user_canvas.go
@@ -17,6 +17,7 @@
package dao
import (
+ "context"
"errors"
"regexp"
"strings"
@@ -85,11 +86,11 @@ func splitUserCanvasTags(raw string) []string {
return tags
}
-func applyUserCanvasTagFilter(query *gorm.DB, tags []string) *gorm.DB {
+func applyUserCanvasTagFilter(ctx context.Context, db *gorm.DB, query *gorm.DB, tags []string) *gorm.DB {
if len(tags) == 0 {
return query
}
- tagQuery := DB.Session(&gorm.Session{NewDB: true})
+ tagQuery := db.WithContext(ctx).Session(&gorm.Session{NewDB: true})
hasTag := false
for _, tag := range tags {
tag = strings.TrimSpace(tag)
@@ -97,7 +98,7 @@ func applyUserCanvasTagFilter(query *gorm.DB, tags []string) *gorm.DB {
continue
}
pattern := "(^|,)[[:space:]]*" + regexp.QuoteMeta(tag) + "[[:space:]]*(,|$)"
- cond := DB.Where("user_canvas.tags REGEXP ?", pattern)
+ cond := db.WithContext(ctx).Where("user_canvas.tags REGEXP ?", pattern)
if !hasTag {
tagQuery = tagQuery.Where(cond)
hasTag = true
@@ -122,14 +123,14 @@ func NewUserCanvasDAO() *UserCanvasDAO {
}
// Create user canvas
-func (dao *UserCanvasDAO) Create(userCanvas *entity.UserCanvas) error {
- return DB.Create(userCanvas).Error
+func (dao *UserCanvasDAO) Create(ctx context.Context, db *gorm.DB, userCanvas *entity.UserCanvas) error {
+ return db.WithContext(ctx).Create(userCanvas).Error
}
// GetByID get user canvas by ID
-func (dao *UserCanvasDAO) GetByID(id string) (*entity.UserCanvas, error) {
+func (dao *UserCanvasDAO) GetByID(ctx context.Context, db *gorm.DB, id string) (*entity.UserCanvas, error) {
var canvas entity.UserCanvas
- err := DB.Where("id = ?", id).First(&canvas).Error
+ err := db.WithContext(ctx).Where("id = ?", id).First(&canvas).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrUserCanvasNotFound
@@ -151,7 +152,7 @@ func (dao *UserCanvasDAO) GetByID(id string) (*entity.UserCanvas, error) {
// canvas — yields ErrUserCanvasNotFound. The single error type stops
// callers from leaking "exists but not yours" vs "doesn't exist" via the
// HTTP status code.
-func (dao *UserCanvasDAO) GetByIDForUser(canvasID, userID string, tenantIDs []string) (*entity.UserCanvas, error) {
+func (dao *UserCanvasDAO) GetByIDForUser(ctx context.Context, db *gorm.DB, canvasID, userID string, tenantIDs []string) (*entity.UserCanvas, error) {
if canvasID == "" {
return nil, ErrUserCanvasNotFound
}
@@ -161,7 +162,7 @@ func (dao *UserCanvasDAO) GetByIDForUser(canvasID, userID string, tenantIDs []st
// owner=userID is allowed regardless of permission, matching the
// ListByTenantIDs predicate used by GET /api/v1/agents.
- ownerOrTeam := DB.Where("user_id = ?", userID)
+ ownerOrTeam := db.WithContext(ctx).Where("user_id = ?", userID)
if len(tenantIDs) > 0 {
ownerOrTeam = ownerOrTeam.Or(
"user_id IN ? AND permission = ?", tenantIDs, "team",
@@ -169,7 +170,7 @@ func (dao *UserCanvasDAO) GetByIDForUser(canvasID, userID string, tenantIDs []st
}
var canvas entity.UserCanvas
- err := DB.Where("id = ?", canvasID).Where(ownerOrTeam).First(&canvas).Error
+ err := db.WithContext(ctx).Where("id = ?", canvasID).Where(ownerOrTeam).First(&canvas).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrUserCanvasNotFound
@@ -180,8 +181,8 @@ func (dao *UserCanvasDAO) GetByIDForUser(canvasID, userID string, tenantIDs []st
}
// Update update user canvas
-func (dao *UserCanvasDAO) Update(userCanvas *entity.UserCanvas) error {
- return DB.Save(userCanvas).Error
+func (dao *UserCanvasDAO) Update(ctx context.Context, db *gorm.DB, userCanvas *entity.UserCanvas) error {
+ return db.WithContext(ctx).Save(userCanvas).Error
}
// Accessible reports whether canvasID is reachable by userID under
@@ -204,7 +205,7 @@ func (dao *UserCanvasDAO) Update(userCanvas *entity.UserCanvas) error {
// Callers that don't have a tenant list handy (rare; most
// handlers derive it from the user context) should call
// GetTenantIDsByUserID first and pass the result.
-func (dao *UserCanvasDAO) Accessible(canvasID, userID string, tenantIDs []string) bool {
+func (dao *UserCanvasDAO) Accessible(ctx context.Context, db *gorm.DB, canvasID, userID string, tenantIDs []string) bool {
if canvasID == "" || userID == "" {
return false
}
@@ -212,14 +213,14 @@ func (dao *UserCanvasDAO) Accessible(canvasID, userID string, tenantIDs []string
// Team-permission canvases are reachable only when the caller is a
// member of one of the owner's tenants — mirrors the predicate in
// GetByIDForUser / ListByTenantIDs.
- ownerOrTeam := DB.Where("user_id = ?", userID)
+ ownerOrTeam := db.WithContext(ctx).Where("user_id = ?", userID)
if len(tenantIDs) > 0 {
ownerOrTeam = ownerOrTeam.Or(
"user_id IN ? AND permission = ?", tenantIDs, "team",
)
}
var canvas entity.UserCanvas
- err := DB.Select("id").
+ err := db.WithContext(ctx).Select("id").
Where("id = ?", canvasID).
Where(ownerOrTeam).
First(&canvas).Error
@@ -230,27 +231,27 @@ func (dao *UserCanvasDAO) Accessible(canvasID, userID string, tenantIDs []string
}
// Delete delete user canvas
-func (dao *UserCanvasDAO) Delete(id string) error {
+func (dao *UserCanvasDAO) Delete(ctx context.Context, db *gorm.DB, id string) error {
// gorm v2 treats the first non-int inline arg as a column name, not a
// primary-key value — passing `id` verbatim produced WHERE ID = ?
// and made MySQL complain about an unknown "AGENT_ID" column. The
// explicit Where+Delete form is the same pattern used by
// API4ConversationDAO.Delete (see api_token.go:142-144).
- return DB.Where("id = ?", id).Delete(&entity.UserCanvas{}).Error
+ return db.WithContext(ctx).Where("id = ?", id).Delete(&entity.UserCanvas{}).Error
}
// UpdateTx is the transactional variant of Update. Callers wrap a sequence
// of *Tx calls in dao.DB.Transaction(func(tx *gorm.DB) error { ... }) so
// multi-step writes (e.g. publish-agent, delete-agent) are atomic.
-func (dao *UserCanvasDAO) UpdateTx(tx *gorm.DB, userCanvas *entity.UserCanvas) error {
- return tx.Save(userCanvas).Error
+func (dao *UserCanvasDAO) UpdateTx(ctx context.Context, tx *gorm.DB, userCanvas *entity.UserCanvas) error {
+ return tx.WithContext(ctx).Save(userCanvas).Error
}
// DeleteTx is the transactional variant of Delete. The canvas must
// already be loaded and access-checked by the caller.
-func (dao *UserCanvasDAO) DeleteTx(tx *gorm.DB, id string) error {
+func (dao *UserCanvasDAO) DeleteTx(ctx context.Context, tx *gorm.DB, id string) error {
// See Delete() above for the rationale on Where("id = ?", id).
- return tx.Where("id = ?", id).Delete(&entity.UserCanvas{}).Error
+ return tx.WithContext(ctx).Where("id = ?", id).Delete(&entity.UserCanvas{}).Error
}
// GetByUserAndTitle returns the canvas matching user_id + title (and
@@ -258,8 +259,8 @@ func (dao *UserCanvasDAO) DeleteTx(tx *gorm.DB, id string) error {
// Used by service.AgentService.CreateAgent to enforce the "title
// already exists" rule that the Python agent API mirrors with
// UserCanvasService.query(user_id=..., title=...).
-func (dao *UserCanvasDAO) GetByUserAndTitle(userID, title, canvasCategory string) (*entity.UserCanvas, error) {
- q := DB.Where("user_id = ? AND title = ?", userID, title)
+func (dao *UserCanvasDAO) GetByUserAndTitle(ctx context.Context, db *gorm.DB, userID, title, canvasCategory string) (*entity.UserCanvas, error) {
+ q := db.WithContext(ctx).Where("user_id = ? AND title = ?", userID, title)
if canvasCategory != "" {
q = q.Where("canvas_category = ?", canvasCategory)
}
@@ -275,9 +276,9 @@ func (dao *UserCanvasDAO) GetByUserAndTitle(userID, title, canvasCategory string
// GetList get canvases list with pagination and filtering
// Similar to Python UserCanvasService.get_list
-func (dao *UserCanvasDAO) GetList(tenantID string, pageNumber, itemsPerPage int, orderby string, desc bool, id, title string, canvasCategory, canvasType string) ([]*entity.UserCanvas, error) {
+func (dao *UserCanvasDAO) GetList(ctx context.Context, db *gorm.DB, tenantID string, pageNumber, itemsPerPage int, orderby string, desc bool, id, title string, canvasCategory, canvasType string) ([]*entity.UserCanvas, error) {
- query := DB.Model(&entity.UserCanvas{}).
+ query := db.WithContext(ctx).Model(&entity.UserCanvas{}).
Where("user_id = ?", tenantID)
if id != "" {
@@ -315,9 +316,9 @@ func (dao *UserCanvasDAO) GetList(tenantID string, pageNumber, itemsPerPage int,
// GetAllCanvasesByTenantIDs get all permitted canvases by tenant IDs
// Similar to Python UserCanvasService.get_all_agents_by_tenant_ids
-func (dao *UserCanvasDAO) GetAllCanvasesByTenantIDs(tenantIDs []string, userID string) ([]*CanvasBasicInfo, error) {
+func (dao *UserCanvasDAO) GetAllCanvasesByTenantIDs(ctx context.Context, db *gorm.DB, tenantIDs []string, userID string) ([]*CanvasBasicInfo, error) {
- query := DB.Model(&entity.UserCanvas{}).
+ query := db.WithContext(ctx).Model(&entity.UserCanvas{}).
Select("id, avatar, title, permission, canvas_type, canvas_category").
Where("user_id IN (?) AND permission = ?", tenantIDs, "team").
Or("user_id = ?", userID).
@@ -349,13 +350,13 @@ type UserCanvasListItem struct {
// ListByTenantIDs lists agent canvases accessible to the given owner IDs with optional
// keyword filter, tag filter, pagination, and ordering.
// Mirrors Python UserCanvasService.get_by_tenant_ids (list route only).
-func (dao *UserCanvasDAO) ListByTenantIDs(ownerIDs []string, userID string, page, pageSize int, orderby string, desc bool, keywords, canvasCategory, canvasType string, tags []string) ([]*UserCanvasListItem, int64, error) {
+func (dao *UserCanvasDAO) ListByTenantIDs(ctx context.Context, db *gorm.DB, ownerIDs []string, userID string, page, pageSize int, orderby string, desc bool, keywords, canvasCategory, canvasType string, tags []string) ([]*UserCanvasListItem, int64, error) {
if len(ownerIDs) == 0 {
return nil, 0, nil
}
// Canvases owned by any of the ownerIDs that are "team"-permission, plus all owned by userID.
- base := DB.Model(&entity.UserCanvas{}).
+ base := db.WithContext(ctx).Model(&entity.UserCanvas{}).
Select(`user_canvas.id,
user_canvas.avatar,
user_canvas.title,
@@ -373,7 +374,7 @@ func (dao *UserCanvasDAO) ListByTenantIDs(ownerIDs []string, userID string, page
Joins("LEFT JOIN user ON user_canvas.user_id = user.id").
Where("user_canvas.user_id IN ?", ownerIDs).
Where(
- DB.Where("user_canvas.permission = ?", "team").
+ db.WithContext(ctx).Where("user_canvas.permission = ?", "team").
Or("user_canvas.user_id = ?", userID))
if canvasCategory != "" {
@@ -388,7 +389,7 @@ func (dao *UserCanvasDAO) ListByTenantIDs(ownerIDs []string, userID string, page
like := "%" + keywords + "%"
base = base.Where("user_canvas.title LIKE ?", like)
}
- base = applyUserCanvasTagFilter(base, tags)
+ base = applyUserCanvasTagFilter(ctx, db, base, tags)
var total int64
if err := base.Count(&total).Error; err != nil {
@@ -415,15 +416,15 @@ func (dao *UserCanvasDAO) ListByTenantIDs(ownerIDs []string, userID string, page
}
// ListTags returns tag usage counts across canvases visible to userID.
-func (dao *UserCanvasDAO) ListTags(ownerIDs []string, userID string, canvasCategory string) (map[string]int, error) {
+func (dao *UserCanvasDAO) ListTags(ctx context.Context, db *gorm.DB, ownerIDs []string, userID string, canvasCategory string) (map[string]int, error) {
if len(ownerIDs) == 0 {
return map[string]int{}, nil
}
- query := DB.Model(&entity.UserCanvas{}).
+ query := db.WithContext(ctx).Model(&entity.UserCanvas{}).
Select("user_canvas.tags").
Where(
- DB.Where("user_canvas.user_id IN ? AND user_canvas.permission = ?", ownerIDs, "team").
+ db.WithContext(ctx).Where("user_canvas.user_id IN ? AND user_canvas.permission = ?", ownerIDs, "team").
Or("user_canvas.user_id = ?", userID),
)
@@ -448,8 +449,8 @@ func (dao *UserCanvasDAO) ListTags(ownerIDs []string, userID string, canvasCateg
}
// GetByCanvasID get user canvas by canvas ID (alias for GetByID)
-func (dao *UserCanvasDAO) GetByCanvasID(canvasID string) (*entity.UserCanvas, error) {
- return dao.GetByID(canvasID)
+func (dao *UserCanvasDAO) GetByCanvasID(ctx context.Context, db *gorm.DB, canvasID string) (*entity.UserCanvas, error) {
+ return dao.GetByID(ctx, db, canvasID)
}
// CanvasBasicInfo basic canvas information for list responses
@@ -463,34 +464,34 @@ type CanvasBasicInfo struct {
}
// DeleteByUserID deletes all canvases by user ID (hard delete)
-func (dao *UserCanvasDAO) DeleteByUserID(userID string) (int64, error) {
- result := DB.Unscoped().Where("user_id = ?", userID).Delete(&entity.UserCanvas{})
+func (dao *UserCanvasDAO) DeleteByUserID(ctx context.Context, db *gorm.DB, userID string) (int64, error) {
+ result := db.WithContext(ctx).Unscoped().Where("user_id = ?", userID).Delete(&entity.UserCanvas{})
return result.RowsAffected, result.Error
}
// GetAllCanvasIDsByUserID gets all canvas IDs by user ID
-func (dao *UserCanvasDAO) GetAllCanvasIDsByUserID(userID string) ([]string, error) {
+func (dao *UserCanvasDAO) GetAllCanvasIDsByUserID(ctx context.Context, db *gorm.DB, userID string) ([]string, error) {
var canvasIDs []string
- err := DB.Model(&entity.UserCanvas{}).
+ err := db.WithContext(ctx).Model(&entity.UserCanvas{}).
Where("user_id = ?", userID).
Pluck("id", &canvasIDs).Error
return canvasIDs, err
}
// UpdateDSL updates a canvas DSL by canvas ID.
-func (dao *UserCanvasDAO) UpdateDSL(canvasID string, dsl entity.JSONMap) (int64, error) {
- result := DB.Model(&entity.UserCanvas{}).Where("id = ?", canvasID).Update("dsl", dsl)
+func (dao *UserCanvasDAO) UpdateDSL(ctx context.Context, db *gorm.DB, canvasID string, dsl entity.JSONMap) (int64, error) {
+ result := db.WithContext(ctx).Model(&entity.UserCanvas{}).Where("id = ?", canvasID).Update("dsl", dsl)
return result.RowsAffected, result.Error
}
// UpdateFields updates only the supplied user_canvas columns.
-func (dao *UserCanvasDAO) UpdateFields(canvasID string, fields map[string]interface{}) (int64, error) {
- result := DB.Model(&entity.UserCanvas{}).Where("id = ?", canvasID).Updates(fields)
+func (dao *UserCanvasDAO) UpdateFields(ctx context.Context, db *gorm.DB, canvasID string, fields map[string]interface{}) (int64, error) {
+ result := db.WithContext(ctx).Model(&entity.UserCanvas{}).Where("id = ?", canvasID).Updates(fields)
return result.RowsAffected, result.Error
}
// UpdateTags updates a canvas's comma-separated tags by canvas ID.
-func (dao *UserCanvasDAO) UpdateTags(canvasID, tags string) (int64, error) {
- result := DB.Model(&entity.UserCanvas{}).Where("id = ?", canvasID).Update("tags", tags)
+func (dao *UserCanvasDAO) UpdateTags(ctx context.Context, db *gorm.DB, canvasID, tags string) (int64, error) {
+ result := db.WithContext(ctx).Model(&entity.UserCanvas{}).Where("id = ?", canvasID).Update("tags", tags)
return result.RowsAffected, result.Error
}
diff --git a/internal/dao/user_canvas_test.go b/internal/dao/user_canvas_test.go
index 36de36bab3..efce6faec0 100644
--- a/internal/dao/user_canvas_test.go
+++ b/internal/dao/user_canvas_test.go
@@ -46,9 +46,10 @@ func TestUserCanvasDAOUpdateDSL(t *testing.T) {
db := setupUserCanvasTestDB(t)
pushDB(t, db)
+ ctx := t.Context()
dao := NewUserCanvasDAO()
originalDSL := entity.JSONMap{"graph": map[string]interface{}{"nodes": []interface{}{"old"}}}
- if err := dao.Create(&entity.UserCanvas{
+ if err := dao.Create(ctx, db, &entity.UserCanvas{
ID: "canvas-1",
UserID: "user-1",
Title: stringPtr("Test Canvas"),
@@ -65,7 +66,7 @@ func TestUserCanvasDAOUpdateDSL(t *testing.T) {
},
"path": []interface{}{"start", "end"},
}
- rows, err := dao.UpdateDSL("canvas-1", newDSL)
+ rows, err := dao.UpdateDSL(ctx, db, "canvas-1", newDSL)
if err != nil {
t.Fatalf("UpdateDSL failed: %v", err)
}
@@ -73,7 +74,7 @@ func TestUserCanvasDAOUpdateDSL(t *testing.T) {
t.Fatalf("expected 1 row affected, got %d", rows)
}
- canvas, err := dao.GetByID("canvas-1")
+ canvas, err := dao.GetByID(ctx, db, "canvas-1")
if err != nil {
t.Fatalf("failed to get canvas: %v", err)
}
@@ -100,10 +101,10 @@ func TestUserCanvasDAOUpdateDSL(t *testing.T) {
func TestUserCanvasDAOUpdateDSLNoMatch(t *testing.T) {
db := setupUserCanvasTestDB(t)
pushDB(t, db)
-
+ ctx := t.Context()
dao := NewUserCanvasDAO()
originalDSL := entity.JSONMap{"path": []interface{}{"old"}}
- if err := dao.Create(&entity.UserCanvas{
+ if err := dao.Create(ctx, db, &entity.UserCanvas{
ID: "canvas-1",
UserID: "user-1",
Title: stringPtr("Test Canvas"),
@@ -113,7 +114,7 @@ func TestUserCanvasDAOUpdateDSLNoMatch(t *testing.T) {
t.Fatalf("failed to create canvas: %v", err)
}
- rows, err := dao.UpdateDSL("missing-canvas", entity.JSONMap{"path": []interface{}{"new"}})
+ rows, err := dao.UpdateDSL(ctx, db, "missing-canvas", entity.JSONMap{"path": []interface{}{"new"}})
if err != nil {
t.Fatalf("UpdateDSL failed: %v", err)
}
@@ -121,7 +122,7 @@ func TestUserCanvasDAOUpdateDSLNoMatch(t *testing.T) {
t.Fatalf("expected 0 rows affected, got %d", rows)
}
- canvas, err := dao.GetByID("canvas-1")
+ canvas, err := dao.GetByID(ctx, db, "canvas-1")
if err != nil {
t.Fatalf("failed to get canvas: %v", err)
}
@@ -159,13 +160,14 @@ func TestUserCanvasDAOListTagsIncludesPipelineWhenCategoryIsEmpty(t *testing.T)
Tags: "pipeline-tag,shared",
},
}
+ ctx := t.Context()
for _, row := range rows {
- if err := dao.Create(row); err != nil {
+ if err := dao.Create(ctx, db, row); err != nil {
t.Fatalf("failed to create canvas %s: %v", row.ID, err)
}
}
- counts, err := dao.ListTags([]string{"user-1"}, "user-1", "")
+ counts, err := dao.ListTags(ctx, db, []string{"user-1"}, "user-1", "")
if err != nil {
t.Fatalf("ListTags failed: %v", err)
}
@@ -179,7 +181,7 @@ func TestUserCanvasDAOListTagsIncludesPipelineWhenCategoryIsEmpty(t *testing.T)
t.Fatalf("shared count = %d, want 2", counts["shared"])
}
- counts, err = dao.ListTags([]string{"user-1"}, "user-1", "agent_canvas")
+ counts, err = dao.ListTags(ctx, db, []string{"user-1"}, "user-1", "agent_canvas")
if err != nil {
t.Fatalf("ListTags with category failed: %v", err)
}
diff --git a/internal/dao/user_canvas_version.go b/internal/dao/user_canvas_version.go
index cb01764c89..aaaa1898a6 100644
--- a/internal/dao/user_canvas_version.go
+++ b/internal/dao/user_canvas_version.go
@@ -17,6 +17,7 @@
package dao
import (
+ "context"
"errors"
"reflect"
@@ -54,16 +55,16 @@ func NewUserCanvasVersionDAO() *UserCanvasVersionDAO {
// Create inserts a new version row. The caller assigns ID, UserCanvasID,
// Title, Description, DSL. CreateTime/UpdateTime are stamped by the
// BaseModel BeforeCreate hook.
-func (dao *UserCanvasVersionDAO) Create(v *entity.UserCanvasVersion) error {
- return DB.Create(v).Error
+func (dao *UserCanvasVersionDAO) Create(ctx context.Context, db *gorm.DB, v *entity.UserCanvasVersion) error {
+ return db.WithContext(ctx).Create(v).Error
}
// GetByID fetches a single version by primary key. Returns
// ErrUserCanvasVersionNotFound when the row is absent so callers can map
// to a 404 instead of inspecting gorm.ErrRecordNotFound directly.
-func (dao *UserCanvasVersionDAO) GetByID(id string) (*entity.UserCanvasVersion, error) {
+func (dao *UserCanvasVersionDAO) GetByID(ctx context.Context, db *gorm.DB, id string) (*entity.UserCanvasVersion, error) {
var v entity.UserCanvasVersion
- err := DB.Where("id = ?", id).First(&v).Error
+ err := db.WithContext(ctx).Where("id = ?", id).First(&v).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrUserCanvasVersionNotFound
@@ -75,9 +76,9 @@ func (dao *UserCanvasVersionDAO) GetByID(id string) (*entity.UserCanvasVersion,
// ListByCanvasID returns every version of the given canvas, ordered by
// create_time DESC so the most recent publish appears first.
-func (dao *UserCanvasVersionDAO) ListByCanvasID(canvasID string) ([]*entity.UserCanvasVersion, error) {
+func (dao *UserCanvasVersionDAO) ListByCanvasID(ctx context.Context, db *gorm.DB, canvasID string) ([]*entity.UserCanvasVersion, error) {
var vs []*entity.UserCanvasVersion
- err := DB.Where("user_canvas_id = ?", canvasID).
+ err := db.WithContext(ctx).Where("user_canvas_id = ?", canvasID).
Order("create_time DESC").
Find(&vs).Error
return vs, err
@@ -85,9 +86,9 @@ func (dao *UserCanvasVersionDAO) ListByCanvasID(canvasID string) ([]*entity.User
// GetLatest returns the most recently created version of canvasID, or
// ErrUserCanvasVersionNotFound when the canvas has never been published.
-func (dao *UserCanvasVersionDAO) GetLatest(canvasID string) (*entity.UserCanvasVersion, error) {
+func (dao *UserCanvasVersionDAO) GetLatest(ctx context.Context, db *gorm.DB, canvasID string) (*entity.UserCanvasVersion, error) {
var v entity.UserCanvasVersion
- err := DB.Where("user_canvas_id = ?", canvasID).
+ err := db.WithContext(ctx).Where("user_canvas_id = ?", canvasID).
Order("create_time DESC").
First(&v).Error
if err != nil {
@@ -100,48 +101,48 @@ func (dao *UserCanvasVersionDAO) GetLatest(canvasID string) (*entity.UserCanvasV
}
// Delete removes a single version by id. No-op when the row is absent.
-func (dao *UserCanvasVersionDAO) Delete(id string) error {
- return DB.Where("id = ?", id).Delete(&entity.UserCanvasVersion{}).Error
+func (dao *UserCanvasVersionDAO) Delete(ctx context.Context, db *gorm.DB, id string) error {
+ return db.WithContext(ctx).Where("id = ?", id).Delete(&entity.UserCanvasVersion{}).Error
}
// DeleteTx is the transactional variant of Delete. Used by
// service.AgentService.DeleteVersion so the version-row removal and the
// (future) parent-canvas stat update land in one atomic write.
-func (dao *UserCanvasVersionDAO) DeleteTx(tx *gorm.DB, id string) error {
- return tx.Where("id = ?", id).Delete(&entity.UserCanvasVersion{}).Error
+func (dao *UserCanvasVersionDAO) DeleteTx(ctx context.Context, tx *gorm.DB, id string) error {
+ return tx.WithContext(ctx).Where("id = ?", id).Delete(&entity.UserCanvasVersion{}).Error
}
// DeleteByCanvasID removes every version of the given canvas. Called from
// the service layer when the parent canvas is deleted to enforce the
// §2.9 cascade rule. Returns the number of rows actually deleted.
-func (dao *UserCanvasVersionDAO) DeleteByCanvasID(canvasID string) (int64, error) {
- res := DB.Where("user_canvas_id = ?", canvasID).Delete(&entity.UserCanvasVersion{})
+func (dao *UserCanvasVersionDAO) DeleteByCanvasID(ctx context.Context, db *gorm.DB, canvasID string) (int64, error) {
+ res := db.WithContext(ctx).Where("user_canvas_id = ?", canvasID).Delete(&entity.UserCanvasVersion{})
return res.RowsAffected, res.Error
}
// DeleteByCanvasIDTx is the transactional variant of DeleteByCanvasID.
// Used by service.AgentService.DeleteAgent so the cascade runs atomically
// with the parent canvas row removal.
-func (dao *UserCanvasVersionDAO) DeleteByCanvasIDTx(tx *gorm.DB, canvasID string) (int64, error) {
- res := tx.Where("user_canvas_id = ?", canvasID).Delete(&entity.UserCanvasVersion{})
+func (dao *UserCanvasVersionDAO) DeleteByCanvasIDTx(ctx context.Context, tx *gorm.DB, canvasID string) (int64, error) {
+ res := tx.WithContext(ctx).Where("user_canvas_id = ?", canvasID).Delete(&entity.UserCanvasVersion{})
return res.RowsAffected, res.Error
}
// CreateTx is the transactional variant of Create.
-func (dao *UserCanvasVersionDAO) CreateTx(tx *gorm.DB, v *entity.UserCanvasVersion) error {
- return tx.Create(v).Error
+func (dao *UserCanvasVersionDAO) CreateTx(ctx context.Context, tx *gorm.DB, v *entity.UserCanvasVersion) error {
+ return tx.WithContext(ctx).Create(v).Error
}
// SaveOrReplaceLatest inserts a new version or refreshes the latest matching
// draft in place. If the latest matching version is released and the current
// save is a draft, it creates a new draft to preserve the released snapshot.
-func (dao *UserCanvasVersionDAO) SaveOrReplaceLatest(opts SaveOrReplaceLatestVersionOptions) (*entity.UserCanvasVersion, error) {
+func (dao *UserCanvasVersionDAO) SaveOrReplaceLatest(ctx context.Context, db *gorm.DB, opts SaveOrReplaceLatestVersionOptions) (*entity.UserCanvasVersion, error) {
if opts.KeepUnpublished <= 0 {
opts.KeepUnpublished = 20
}
var saved *entity.UserCanvasVersion
- if err := DB.Transaction(func(tx *gorm.DB) error {
- row, err := dao.SaveOrReplaceLatestTx(tx, opts)
+ if err := db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ row, err := dao.SaveOrReplaceLatestTx(ctx, tx, opts)
if err != nil {
return err
}
@@ -155,14 +156,14 @@ func (dao *UserCanvasVersionDAO) SaveOrReplaceLatest(opts SaveOrReplaceLatestVer
// SaveOrReplaceLatestTx inserts or refreshes a version using the caller's
// transaction. Its write semantics match SaveOrReplaceLatest exactly.
-func (dao *UserCanvasVersionDAO) SaveOrReplaceLatestTx(tx *gorm.DB, opts SaveOrReplaceLatestVersionOptions) (*entity.UserCanvasVersion, error) {
+func (dao *UserCanvasVersionDAO) SaveOrReplaceLatestTx(ctx context.Context, tx *gorm.DB, opts SaveOrReplaceLatestVersionOptions) (*entity.UserCanvasVersion, error) {
if opts.KeepUnpublished <= 0 {
opts.KeepUnpublished = 20
}
var parent struct {
ID string
}
- if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
+ if err := tx.WithContext(ctx).Clauses(clause.Locking{Strength: "UPDATE"}).
Table((&entity.UserCanvas{}).TableName()).
Select("id").
Where("id = ?", opts.UserCanvasID).
@@ -171,7 +172,7 @@ func (dao *UserCanvasVersionDAO) SaveOrReplaceLatestTx(tx *gorm.DB, opts SaveOrR
}
var latest entity.UserCanvasVersion
- err := tx.Where("user_canvas_id = ?", opts.UserCanvasID).
+ err := tx.WithContext(ctx).Where("user_canvas_id = ?", opts.UserCanvasID).
Order("create_time DESC, id DESC").
First(&latest).Error
if err != nil {
@@ -190,7 +191,7 @@ func (dao *UserCanvasVersionDAO) SaveOrReplaceLatestTx(tx *gorm.DB, opts SaveOrR
if opts.Description != nil {
updates["description"] = opts.Description
}
- if err := tx.Model(&entity.UserCanvasVersion{}).
+ if err = tx.WithContext(ctx).Model(&entity.UserCanvasVersion{}).
Where("id = ?", latest.ID).
Updates(updates).Error; err != nil {
return nil, err
@@ -203,7 +204,7 @@ func (dao *UserCanvasVersionDAO) SaveOrReplaceLatestTx(tx *gorm.DB, opts SaveOrR
if opts.Description != nil {
latest.Description = opts.Description
}
- return &latest, dao.deleteAllUnpublishedExcessTx(tx, opts.UserCanvasID, opts.KeepUnpublished)
+ return &latest, dao.deleteAllUnpublishedExcessTx(ctx, tx, opts.UserCanvasID, opts.KeepUnpublished)
}
}
row := &entity.UserCanvasVersion{
@@ -214,10 +215,10 @@ func (dao *UserCanvasVersionDAO) SaveOrReplaceLatestTx(tx *gorm.DB, opts SaveOrR
Release: opts.Release,
DSL: opts.DSL,
}
- if err := tx.Create(row).Error; err != nil {
+ if err = tx.WithContext(ctx).Create(row).Error; err != nil {
return nil, err
}
- return row, dao.deleteAllUnpublishedExcessTx(tx, opts.UserCanvasID, opts.KeepUnpublished)
+ return row, dao.deleteAllUnpublishedExcessTx(ctx, tx, opts.UserCanvasID, opts.KeepUnpublished)
}
func (opts SaveOrReplaceLatestVersionOptions) sameDSL(dsl entity.JSONMap) bool {
@@ -227,19 +228,12 @@ func (opts SaveOrReplaceLatestVersionOptions) sameDSL(dsl entity.JSONMap) bool {
return reflect.DeepEqual(dsl, opts.DSL)
}
-// DeleteAllUnpublishedExcess keeps the newest keep unpublished versions for a
-// canvas and deletes older unpublished rows. Released versions are never
-// removed by this cleanup.
-func (dao *UserCanvasVersionDAO) DeleteAllUnpublishedExcess(canvasID string, keep int) error {
- return dao.deleteAllUnpublishedExcessTx(DB, canvasID, keep)
-}
-
-func (dao *UserCanvasVersionDAO) deleteAllUnpublishedExcessTx(tx *gorm.DB, canvasID string, keep int) error {
+func (dao *UserCanvasVersionDAO) deleteAllUnpublishedExcessTx(ctx context.Context, tx *gorm.DB, canvasID string, keep int) error {
if keep < 0 {
keep = 0
}
var ids []string
- if err := tx.Model(&entity.UserCanvasVersion{}).
+ if err := tx.WithContext(ctx).Model(&entity.UserCanvasVersion{}).
Where(map[string]interface{}{"user_canvas_id": canvasID, "release": false}).
Order("create_time DESC").
Pluck("id", &ids).Error; err != nil {
@@ -249,5 +243,5 @@ func (dao *UserCanvasVersionDAO) deleteAllUnpublishedExcessTx(tx *gorm.DB, canva
return nil
}
ids = ids[keep:]
- return tx.Where("id IN ?", ids).Delete(&entity.UserCanvasVersion{}).Error
+ return tx.WithContext(ctx).Where("id IN ?", ids).Delete(&entity.UserCanvasVersion{}).Error
}
diff --git a/internal/dao/user_canvas_version_test.go b/internal/dao/user_canvas_version_test.go
index 454e0bf6fe..5ecc50509b 100644
--- a/internal/dao/user_canvas_version_test.go
+++ b/internal/dao/user_canvas_version_test.go
@@ -17,10 +17,13 @@
package dao
import (
+ "context"
"errors"
"testing"
"ragflow/internal/entity"
+
+ "gorm.io/gorm"
)
// TestUserCanvasVersionDAO_Constructor verifies the DAO constructor returns
@@ -61,14 +64,13 @@ func TestUserCanvasVersionDAO_NotFoundSentinel(t *testing.T) {
// UserCanvasVersionDAO. Asserting at compile time that the concrete DAO
// satisfies it prevents accidental signature drift in future refactors.
type daoInterface interface {
- Create(v *entity.UserCanvasVersion) error
- GetByID(id string) (*entity.UserCanvasVersion, error)
- ListByCanvasID(canvasID string) ([]*entity.UserCanvasVersion, error)
- GetLatest(canvasID string) (*entity.UserCanvasVersion, error)
- SaveOrReplaceLatest(opts SaveOrReplaceLatestVersionOptions) (*entity.UserCanvasVersion, error)
- Delete(id string) error
- DeleteByCanvasID(canvasID string) (int64, error)
- DeleteAllUnpublishedExcess(canvasID string, keep int) error
+ Create(ctx context.Context, db *gorm.DB, v *entity.UserCanvasVersion) error
+ GetByID(ctx context.Context, db *gorm.DB, id string) (*entity.UserCanvasVersion, error)
+ ListByCanvasID(ctx context.Context, db *gorm.DB, canvasID string) ([]*entity.UserCanvasVersion, error)
+ GetLatest(ctx context.Context, db *gorm.DB, canvasID string) (*entity.UserCanvasVersion, error)
+ SaveOrReplaceLatest(ctx context.Context, db *gorm.DB, opts SaveOrReplaceLatestVersionOptions) (*entity.UserCanvasVersion, error)
+ Delete(ctx context.Context, db *gorm.DB, id string) error
+ DeleteByCanvasID(ctx context.Context, db *gorm.DB, canvasID string) (int64, error)
}
var _ daoInterface = (*UserCanvasVersionDAO)(nil)
diff --git a/internal/dao/user_tenant.go b/internal/dao/user_tenant.go
index ee63c3d889..bed281a123 100644
--- a/internal/dao/user_tenant.go
+++ b/internal/dao/user_tenant.go
@@ -21,6 +21,8 @@ import (
"fmt"
"ragflow/internal/entity"
+
+ "gorm.io/gorm"
)
// UserTenantDAO user tenant data access object
@@ -31,54 +33,49 @@ func NewUserTenantDAO() *UserTenantDAO {
return &UserTenantDAO{}
}
-// Create create user tenant relationship
-func (dao *UserTenantDAO) Create(userTenant *entity.UserTenant) error {
- return DB.Create(userTenant).Error
+// Create user tenant relationship
+func (dao *UserTenantDAO) Create(ctx context.Context, db *gorm.DB, userTenant *entity.UserTenant) error {
+ return db.WithContext(ctx).Create(userTenant).Error
}
// GetByID get user tenant relationship by ID
-func (dao *UserTenantDAO) GetByID(id string) (*entity.UserTenant, error) {
+func (dao *UserTenantDAO) GetByID(ctx context.Context, db *gorm.DB, id string) (*entity.UserTenant, error) {
var userTenant entity.UserTenant
- err := DB.Where("id = ? AND status = ?", id, "1").First(&userTenant).Error
+ err := db.WithContext(ctx).Where("id = ? AND status = ?", id, "1").First(&userTenant).Error
if err != nil {
return nil, err
}
return &userTenant, nil
}
-// Update update user tenant relationship
-func (dao *UserTenantDAO) Update(userTenant *entity.UserTenant) error {
- return DB.Save(userTenant).Error
+// Update user tenant relationship
+func (dao *UserTenantDAO) Update(ctx context.Context, db *gorm.DB, userTenant *entity.UserTenant) error {
+ return db.WithContext(ctx).Save(userTenant).Error
}
// Delete delete user tenant relationship (soft delete by setting status to "0")
-func (dao *UserTenantDAO) Delete(id string) error {
- return DB.Model(&entity.UserTenant{}).Where("id = ?", id).Update("status", "0").Error
-}
-
-// GetByUserID get user tenant relationships by user ID
-func (dao *UserTenantDAO) GetByUserID(userID string) ([]*entity.UserTenant, error) {
- return dao.GetByUserIDWithContext(context.Background(), userID)
+func (dao *UserTenantDAO) Delete(ctx context.Context, db *gorm.DB, id string) error {
+ return db.WithContext(ctx).Model(&entity.UserTenant{}).Where("id = ?", id).Update("status", "0").Error
}
-// GetByUserIDWithContext gets active user tenant relationships by user ID with context.
-func (dao *UserTenantDAO) GetByUserIDWithContext(ctx context.Context, userID string) ([]*entity.UserTenant, error) {
+// GetByUserID gets active user tenant relationships by user ID with context.
+func (dao *UserTenantDAO) GetByUserID(ctx context.Context, db *gorm.DB, userID string) ([]*entity.UserTenant, error) {
var relations []*entity.UserTenant
- err := DB.WithContext(ctx).Where("user_id = ? AND status = ?", userID, "1").Find(&relations).Error
+ err := db.WithContext(ctx).Where("user_id = ? AND status = ?", userID, "1").Find(&relations).Error
return relations, err
}
// GetByTenantID get user tenant relationships by tenant ID
-func (dao *UserTenantDAO) GetByTenantID(tenantID string) ([]*entity.UserTenant, error) {
+func (dao *UserTenantDAO) GetByTenantID(ctx context.Context, db *gorm.DB, tenantID string) ([]*entity.UserTenant, error) {
var relations []*entity.UserTenant
- err := DB.Where("tenant_id = ? AND status = ?", tenantID, "1").Find(&relations).Error
+ err := db.WithContext(ctx).Where("tenant_id = ? AND status = ?", tenantID, "1").Find(&relations).Error
return relations, err
}
// GetTenantIDsByUserID get tenant ID list by user ID
-func (dao *UserTenantDAO) GetTenantIDsByUserID(userID string) ([]string, error) {
+func (dao *UserTenantDAO) GetTenantIDsByUserID(ctx context.Context, db *gorm.DB, userID string) ([]string, error) {
var tenantIDs []string
- err := DB.Model(&entity.UserTenant{}).
+ err := db.WithContext(ctx).Model(&entity.UserTenant{}).
Select("tenant_id").
Where("user_id = ? AND status = ?", userID, "1").
Pluck("tenant_id", &tenantIDs).Error
@@ -86,9 +83,9 @@ func (dao *UserTenantDAO) GetTenantIDsByUserID(userID string) ([]string, error)
}
// FilterByUserIDAndTenantID filter user tenant relationship by user ID and tenant ID
-func (dao *UserTenantDAO) FilterByUserIDAndTenantID(userID, tenantID string) (*entity.UserTenant, error) {
+func (dao *UserTenantDAO) FilterByUserIDAndTenantID(ctx context.Context, db *gorm.DB, userID, tenantID string) (*entity.UserTenant, error) {
var userTenant entity.UserTenant
- err := DB.Where("user_id = ? AND tenant_id = ? AND status = ?", userID, tenantID, "1").
+ err := db.WithContext(ctx).Where("user_id = ? AND tenant_id = ? AND status = ?", userID, tenantID, "1").
First(&userTenant).Error
if err != nil {
return nil, err
@@ -97,16 +94,16 @@ func (dao *UserTenantDAO) FilterByUserIDAndTenantID(userID, tenantID string) (*e
}
// GetByUserIDAndRole get user tenant relationships by user ID and role
-func (dao *UserTenantDAO) GetByUserIDAndRole(userID, role string) ([]*entity.UserTenant, error) {
+func (dao *UserTenantDAO) GetByUserIDAndRole(ctx context.Context, db *gorm.DB, userID, role string) ([]*entity.UserTenant, error) {
var relations []*entity.UserTenant
- err := DB.Where("user_id = ? AND role = ? AND status = ?", userID, role, "1").Find(&relations).Error
+ err := db.WithContext(ctx).Where("user_id = ? AND role = ? AND status = ?", userID, role, "1").Find(&relations).Error
return relations, err
}
// GetNumMembers get number of members in a tenant (excluding owner)
-func (dao *UserTenantDAO) GetNumMembers(tenantID string) (int64, error) {
+func (dao *UserTenantDAO) GetNumMembers(ctx context.Context, db *gorm.DB, tenantID string) (int64, error) {
var count int64
- err := DB.Model(&entity.UserTenant{}).
+ err := db.WithContext(ctx).Model(&entity.UserTenant{}).
Where("tenant_id = ? AND status = ? AND role != ?", tenantID, "1", "owner").
Count(&count).Error
return count, err
@@ -140,9 +137,9 @@ type TenantMemberItem struct {
// GetMembersByTenantID returns all non-owner members of a tenant with user details.
// update_date is formatted as "2006-01-02T15:04:05" (no timezone) to match the Python API.
-func (dao *UserTenantDAO) GetMembersByTenantID(tenantID string) ([]*TenantMemberItem, error) {
+func (dao *UserTenantDAO) GetMembersByTenantID(ctx context.Context, db *gorm.DB, tenantID string) ([]*TenantMemberItem, error) {
var results []*TenantMemberItem
- err := DB.Table("user_tenant").
+ err := db.WithContext(ctx).Table("user_tenant").
Select("user_tenant.id, user_tenant.user_id, user_tenant.role, user_tenant.status, "+
"user.nickname, user.email, user.avatar, user.is_authenticated, "+
"user.status AS is_active, user.is_anonymous, user.is_superuser, "+
@@ -155,9 +152,9 @@ func (dao *UserTenantDAO) GetMembersByTenantID(tenantID string) ([]*TenantMember
}
// GetTenantsByUserID get tenants by user ID with user details
-func (dao *UserTenantDAO) GetTenantsByUserID(userID string) ([]*TenantInfoByUserID, error) {
+func (dao *UserTenantDAO) GetTenantsByUserID(ctx context.Context, db *gorm.DB, userID string) ([]*TenantInfoByUserID, error) {
var results []*TenantInfoByUserID
- err := DB.Table("user_tenant").
+ err := db.WithContext(ctx).Table("user_tenant").
Select("user_tenant.tenant_id, user_tenant.role, user.nickname, user.email, user.avatar, user.update_date").
Joins("JOIN user ON user_tenant.tenant_id = user.id AND user_tenant.user_id = ? AND user_tenant.status = ?", userID, "1").
Where("user_tenant.status = ?", "1").
@@ -166,35 +163,35 @@ func (dao *UserTenantDAO) GetTenantsByUserID(userID string) ([]*TenantInfoByUser
}
// DeleteByUserID delete user tenant relationships by user ID (hard delete)
-func (dao *UserTenantDAO) DeleteByUserID(userID string) (int64, error) {
- result := DB.Unscoped().Where("user_id = ?", userID).Delete(&entity.UserTenant{})
+func (dao *UserTenantDAO) DeleteByUserID(ctx context.Context, db *gorm.DB, userID string) (int64, error) {
+ result := db.WithContext(ctx).Unscoped().Where("user_id = ?", userID).Delete(&entity.UserTenant{})
return result.RowsAffected, result.Error
}
// DeleteByTenantID delete user tenant relationships by tenant ID (hard delete)
-func (dao *UserTenantDAO) DeleteByTenantID(tenantID string) (int64, error) {
- result := DB.Unscoped().Where("tenant_id = ?", tenantID).Delete(&entity.UserTenant{})
+func (dao *UserTenantDAO) DeleteByTenantID(ctx context.Context, db *gorm.DB, tenantID string) (int64, error) {
+ result := db.WithContext(ctx).Unscoped().Where("tenant_id = ?", tenantID).Delete(&entity.UserTenant{})
return result.RowsAffected, result.Error
}
// GetByUserIDAll get all user tenant relationships by user ID (including deleted)
-func (dao *UserTenantDAO) GetByUserIDAll(userID string) ([]*entity.UserTenant, error) {
+func (dao *UserTenantDAO) GetByUserIDAll(ctx context.Context, db *gorm.DB, userID string) ([]*entity.UserTenant, error) {
var relations []*entity.UserTenant
- err := DB.Where("user_id = ?", userID).Find(&relations).Error
+ err := db.WithContext(ctx).Where("user_id = ?", userID).Find(&relations).Error
return relations, err
}
// DeleteByUserAndTenant hard-deletes the join record for a specific user+tenant pair.
-func (dao *UserTenantDAO) DeleteByUserAndTenant(userID, tenantID string) error {
- return DB.Unscoped().
+func (dao *UserTenantDAO) DeleteByUserAndTenant(ctx context.Context, db *gorm.DB, userID, tenantID string) error {
+ return db.WithContext(ctx).Unscoped().
Where("user_id = ? AND tenant_id = ?", userID, tenantID).
Delete(&entity.UserTenant{}).Error
}
// UpdateRoleByUserAndTenant updates the role for a specific user+tenant pair.
// Returns an error if no matching row was found.
-func (dao *UserTenantDAO) UpdateRoleByUserAndTenant(userID, tenantID, role string) error {
- result := DB.Model(&entity.UserTenant{}).
+func (dao *UserTenantDAO) UpdateRoleByUserAndTenant(ctx context.Context, db *gorm.DB, userID, tenantID, role string) error {
+ result := db.WithContext(ctx).Model(&entity.UserTenant{}).
Where("user_id = ? AND tenant_id = ? AND status = ?", userID, tenantID, "1").
Update("role", role)
if result.Error != nil {
diff --git a/internal/handler/agent.go b/internal/handler/agent.go
index 08fd8ef27d..9583f3fd3f 100644
--- a/internal/handler/agent.go
+++ b/internal/handler/agent.go
@@ -177,8 +177,10 @@ func (h *AgentHandler) ListAgents(c *gin.Context) {
}
}
}
+ ctx := c.Request.Context()
result, code, err := h.agentService.ListAgents(
+ ctx,
user.ID,
keywords,
page,
@@ -672,8 +674,8 @@ func (h *AgentHandler) ListAgentTags(c *gin.Context) {
common.ResponseWithCodeData(c, code, nil, msg)
return
}
-
- rows, errCode, err := h.agentService.ListAgentTags(user.ID, strings.TrimSpace(c.Query("canvas_category")))
+ ctx := c.Request.Context()
+ rows, errCode, err := h.agentService.ListAgentTags(ctx, user.ID, strings.TrimSpace(c.Query("canvas_category")))
if err != nil {
common.ResponseWithCodeData(c, errCode, nil, err.Error())
return
@@ -697,7 +699,8 @@ func (h *AgentHandler) UpdateAgentTags(c *gin.Context) {
common.ResponseWithCodeData(c, common.CodeArgumentError, nil, "Invalid request: "+err.Error())
return
}
- ok, errCode, errMsg := h.agentService.UpdateAgentTags(user.ID, canvasID, body.Tags)
+ ctx := c.Request.Context()
+ ok, errCode, errMsg := h.agentService.UpdateAgentTags(ctx, user.ID, canvasID, body.Tags)
if !ok {
common.ResponseWithCodeData(c, errCode, nil, errMsg.Error())
return
@@ -1332,7 +1335,8 @@ func (h *AgentHandler) GetAgentWebhookLogs(c *gin.Context) {
return
}
canvasID := c.Param("canvas_id")
- ok, err := h.agentService.CheckCanvasAccess(user.ID, canvasID)
+ ctx := c.Request.Context()
+ ok, err := h.agentService.CheckCanvasAccess(ctx, user.ID, canvasID)
if err != nil || !ok {
// CheckCanvasAccess now surfaces ErrUserCanvasNotFound when
// the canvas row is missing; the Python envelope is
@@ -1357,7 +1361,8 @@ func (h *AgentHandler) GetAgentWebhookLogs(c *gin.Context) {
// the access-denied envelope with the same shape the existing
// loadCanvasForUser-based handlers use.
func (h *AgentHandler) checkCanvasAccessForHandler(c *gin.Context, userID, canvasID string) (bool, common.ErrorCode, string) {
- ok, err := h.agentService.CheckCanvasAccess(userID, canvasID)
+ ctx := c.Request.Context()
+ ok, err := h.agentService.CheckCanvasAccess(ctx, userID, canvasID)
if err != nil {
// The Python agent API uses @_require_canvas_access_async on
// /sessions and /logs/:message_id, which folds "canvas does
diff --git a/internal/handler/api_token.go b/internal/handler/api_token.go
index d7f158f2e6..d74facbf64 100644
--- a/internal/handler/api_token.go
+++ b/internal/handler/api_token.go
@@ -43,14 +43,15 @@ func (h *SystemHandler) ListAPIKeys(c *gin.Context) {
// Get user's tenant with owner role
userTenantDAO := dao.NewUserTenantDAO()
- tenants, err := userTenantDAO.GetByUserIDAndRole(userModel.ID, "owner")
+ ctx := c.Request.Context()
+
+ tenants, err := userTenantDAO.GetByUserIDAndRole(ctx, dao.DB, userModel.ID, "owner")
if err != nil || len(tenants) == 0 {
common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, "Tenant not found")
return
}
tenantID := tenants[0].TenantID
- ctx := c.Request.Context()
// Get keys for the tenant
keys, err := h.systemService.ListAPIKeys(ctx, tenantID)
@@ -78,7 +79,9 @@ func (h *SystemHandler) CreateKey(c *gin.Context) {
// Get user's tenant with owner role
userTenantDAO := dao.NewUserTenantDAO()
- tenants, err := userTenantDAO.GetByUserIDAndRole(userModel.ID, "owner")
+ ctx := c.Request.Context()
+
+ tenants, err := userTenantDAO.GetByUserIDAndRole(ctx, dao.DB, userModel.ID, "owner")
if err != nil || len(tenants) == 0 {
common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, "Tenant not found")
return
@@ -93,8 +96,6 @@ func (h *SystemHandler) CreateKey(c *gin.Context) {
return
}
- ctx := c.Request.Context()
-
// Create key
key, err := h.systemService.CreateAPIKey(ctx, tenantID, &req)
if err != nil {
@@ -118,10 +119,12 @@ func (h *SystemHandler) DeleteKey(c *gin.Context) {
common.ResponseWithHttpCodeData(c, http.StatusInternalServerError, 500, nil, "Invalid user data")
return
}
+ ctx := c.Request.Context()
// Get user's tenant with owner role
userTenantDAO := dao.NewUserTenantDAO()
- tenants, err := userTenantDAO.GetByUserIDAndRole(userModel.ID, "owner")
+
+ tenants, err := userTenantDAO.GetByUserIDAndRole(ctx, dao.DB, userModel.ID, "owner")
if err != nil || len(tenants) == 0 {
common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, "Tenant not found")
return
@@ -136,8 +139,6 @@ func (h *SystemHandler) DeleteKey(c *gin.Context) {
return
}
- ctx := c.Request.Context()
-
// Delete key
if err = h.systemService.DeleteAPIKey(ctx, tenantID, key); err != nil {
common.ResponseWithHttpCodeData(c, http.StatusInternalServerError, 500, nil, "Failed to delete key")
diff --git a/internal/handler/chat.go b/internal/handler/chat.go
index ab3938566c..4f4ac62b60 100644
--- a/internal/handler/chat.go
+++ b/internal/handler/chat.go
@@ -238,7 +238,7 @@ func (h *ChatHandler) DeleteChat(c *gin.Context) {
ctx := c.Request.Context()
if err := h.chatService.DeleteChat(ctx, userID, chatID); err != nil {
if err.Error() == "no authorization" {
- common.ResponseWithCodeData(c, common.CodeAuthenticationError, false, "No authorization.")
+ common.ResponseWithCodeData(c, common.CodeAuthenticationError, false, "no authorization")
return
}
common.ErrorWithCode(c, common.CodeDataError, err.Error())
@@ -272,7 +272,7 @@ func (h *ChatHandler) BulkDeleteChats(c *gin.Context) {
if req.ChatID != "" {
if err := h.chatService.DeleteChat(ctx, userID, req.ChatID); err != nil {
if err.Error() == "no authorization" {
- common.ResponseWithCodeData(c, common.CodeAuthenticationError, false, "No authorization.")
+ common.ResponseWithCodeData(c, common.CodeAuthenticationError, false, "no authorization")
return
}
common.ResponseWithCodeData(c, common.CodeDataError, nil, err.Error())
@@ -338,7 +338,7 @@ func (h *ChatHandler) GetChat(c *gin.Context) {
errMsg := err.Error()
// Check if it's an authorization error
if errMsg == "no authorization" {
- common.ResponseWithCodeData(c, common.CodeAuthenticationError, false, "No authorization.")
+ common.ResponseWithCodeData(c, common.CodeAuthenticationError, false, "no authorization")
return
}
// Not found error
@@ -420,7 +420,7 @@ func (h *ChatHandler) updateChatByMethod(c *gin.Context, patch bool) {
}
if err != nil {
if err.Error() == "no authorization" {
- common.ResponseWithCodeData(c, common.CodeAuthenticationError, false, "No authorization.")
+ common.ResponseWithCodeData(c, common.CodeAuthenticationError, false, "no authorization")
return
}
common.ResponseWithCodeData(c, common.CodeDataError, nil, err.Error())
diff --git a/internal/handler/chat_channel.go b/internal/handler/chat_channel.go
index 351b4cc65c..d7ee024476 100644
--- a/internal/handler/chat_channel.go
+++ b/internal/handler/chat_channel.go
@@ -205,7 +205,7 @@ func unwrapChatChannelPayload(payload map[string]interface{}) map[string]interfa
}
func writeChatChannelError(c *gin.Context, code common.ErrorCode, message string) {
- if code == common.CodeAuthenticationError && message == "No authorization." {
+ if code == common.CodeAuthenticationError && message == "no authorization" {
common.ResponseWithCodeData(c, code, false, message)
return
}
diff --git a/internal/handler/chat_channel_test.go b/internal/handler/chat_channel_test.go
index c925fdd34b..7cb98d4abc 100644
--- a/internal/handler/chat_channel_test.go
+++ b/internal/handler/chat_channel_test.go
@@ -232,7 +232,7 @@ func TestChatChannelHandlerGetChatChannelUnauthorized(t *testing.T) {
h := &ChatChannelHandler{
chatChannelService: fakeChatChannelService{
getFn: func(userID, channelID string) (*entity.ChatChannel, common.ErrorCode, error) {
- return nil, common.CodeAuthenticationError, errors.New("No authorization.")
+ return nil, common.CodeAuthenticationError, errors.New("no authorization")
},
},
}
diff --git a/internal/handler/chat_test.go b/internal/handler/chat_test.go
index 2f49ce00cd..f38623b7bd 100644
--- a/internal/handler/chat_test.go
+++ b/internal/handler/chat_test.go
@@ -195,7 +195,7 @@ func TestUpdateChatHandlerRejectsNonOwner(t *testing.T) {
if resp["data"] != false {
t.Fatalf("expected data=false, got %v", resp["data"])
}
- if resp["message"] != "No authorization." {
+ if resp["message"] != "no authorization" {
t.Fatalf("unexpected message: %v", resp["message"])
}
}
@@ -224,7 +224,7 @@ func TestGetChatHandlerRejectsNonOwner(t *testing.T) {
if resp["data"] != false {
t.Fatalf("expected data=false, got %v", resp["data"])
}
- if resp["message"] != "No authorization." {
+ if resp["message"] != "no authorization" {
t.Fatalf("unexpected message: %v", resp["message"])
}
}
@@ -250,7 +250,7 @@ func TestDeleteChatHandlerRejectsNonOwner(t *testing.T) {
if resp["code"] != float64(common.CodeAuthenticationError) {
t.Fatalf("expected auth error code 109, got %v", resp["code"])
}
- if resp["message"] != "No authorization." {
+ if resp["message"] != "no authorization" {
t.Fatalf("unexpected message: %v", resp["message"])
}
}
diff --git a/internal/handler/connector.go b/internal/handler/connector.go
index 2fbde2534d..ce1aac2bcc 100644
--- a/internal/handler/connector.go
+++ b/internal/handler/connector.go
@@ -97,7 +97,7 @@ func connectorErrorResponse(c *gin.Context, err error) bool {
case err == nil:
return false
case errors.Is(err, service.ErrConnectorNoAuth):
- common.ResponseWithCodeData(c, common.CodeAuthenticationError, false, "No authorization.")
+ common.ResponseWithCodeData(c, common.CodeAuthenticationError, false, "no authorization")
case errors.Is(err, service.ErrConnectorNotFound):
common.ResponseWithCodeData(c, common.CodeDataError, nil, "Can't find this Connector!")
case errors.Is(err, service.ErrConnectorTestUnsupported):
diff --git a/internal/handler/connector_test.go b/internal/handler/connector_test.go
index 506e6c85b2..676b9411c7 100644
--- a/internal/handler/connector_test.go
+++ b/internal/handler/connector_test.go
@@ -292,10 +292,10 @@ func TestConnectorHandlerDeleteConnector(t *testing.T) {
},
{
name: "unauthorized",
- service: fakeConnectorService{code: common.CodeAuthenticationError, err: fmt.Errorf("No authorization.")},
+ service: fakeConnectorService{code: common.CodeAuthenticationError, err: fmt.Errorf("no authorization")},
wantCode: common.CodeAuthenticationError,
wantData: nil,
- wantMsg: "No authorization.",
+ wantMsg: "no authorization",
},
}
@@ -386,9 +386,9 @@ func TestConnectorHandlerListLogs(t *testing.T) {
},
{
name: "unauthorized",
- service: fakeConnectorService{code: common.CodeAuthenticationError, err: fmt.Errorf("No authorization.")},
+ service: fakeConnectorService{code: common.CodeAuthenticationError, err: fmt.Errorf("no authorization")},
wantCode: common.CodeAuthenticationError,
- wantMsg: "No authorization.",
+ wantMsg: "no authorization",
},
}
diff --git a/internal/handler/document.go b/internal/handler/document.go
index e29e569cea..3d1f35d240 100644
--- a/internal/handler/document.go
+++ b/internal/handler/document.go
@@ -309,7 +309,7 @@ func (h *DocumentHandler) UpdateDocument(c *gin.Context) {
return
}
if !h.datasetService.Accessible(ctx, doc.KbID, user.ID) {
- common.ResponseWithCodeData(c, common.CodeAuthenticationError, nil, "No authorization.")
+ common.ResponseWithCodeData(c, common.CodeAuthenticationError, nil, "no authorization")
return
}
@@ -362,7 +362,7 @@ func (h *DocumentHandler) DeleteDocument(c *gin.Context) {
return
}
if !h.datasetService.Accessible(ctx, doc.KbID, user.ID) {
- common.ResponseWithCodeData(c, common.CodeAuthenticationError, nil, "No authorization.")
+ common.ResponseWithCodeData(c, common.CodeAuthenticationError, nil, "no authorization")
return
}
@@ -837,7 +837,7 @@ func (h *DocumentHandler) UploadDocuments(c *gin.Context) {
return
}
if !h.datasetService.CheckKBTeamPermission(ctx, kb, tenantID) {
- common.ResponseWithCodeData(c, common.CodeAuthenticationError, nil, "No authorization.")
+ common.ResponseWithCodeData(c, common.CodeAuthenticationError, nil, "no authorization")
return
}
@@ -1238,7 +1238,7 @@ func (h *DocumentHandler) SetMeta(c *gin.Context) {
return
}
if !h.datasetService.Accessible(ctx, doc.KbID, user.ID) {
- common.ResponseWithCodeData(c, common.CodeAuthenticationError, nil, "No authorization.")
+ common.ResponseWithCodeData(c, common.CodeAuthenticationError, nil, "no authorization")
return
}
@@ -1333,7 +1333,7 @@ func (h *DocumentHandler) DeleteMeta(c *gin.Context) {
return
}
if !h.datasetService.Accessible(ctx, doc.KbID, user.ID) {
- common.ResponseWithCodeData(c, common.CodeAuthenticationError, nil, "No authorization.")
+ common.ResponseWithCodeData(c, common.CodeAuthenticationError, nil, "no authorization")
return
}
diff --git a/internal/handler/document_test.go b/internal/handler/document_test.go
index 7a2c9e5204..fe602412d0 100644
--- a/internal/handler/document_test.go
+++ b/internal/handler/document_test.go
@@ -329,7 +329,7 @@ func TestSetMetaHandler_NotAccessible(t *testing.T) {
if resp["code"] != float64(common.CodeAuthenticationError) {
t.Fatalf("expected auth error, got %v", resp)
}
- if resp["message"] != "No authorization." {
+ if resp["message"] != "no authorization" {
t.Fatalf("unexpected message: %v", resp["message"])
}
if fake.setMetaCalled {
@@ -397,7 +397,7 @@ func TestDeleteDocumentHandler_NotAccessible(t *testing.T) {
if resp["code"] != float64(common.CodeAuthenticationError) {
t.Fatalf("expected auth error, got %v", resp)
}
- if resp["message"] != "No authorization." {
+ if resp["message"] != "no authorization" {
t.Fatalf("unexpected message: %v", resp["message"])
}
if fake.deleteCalled {
@@ -463,7 +463,7 @@ func TestUpdateDocumentHandler_NotAccessible(t *testing.T) {
if resp["code"] != float64(common.CodeAuthenticationError) {
t.Fatalf("expected auth error, got %v", resp)
}
- if resp["message"] != "No authorization." {
+ if resp["message"] != "no authorization" {
t.Fatalf("unexpected message: %v", resp["message"])
}
if fake.updateCalled {
@@ -931,7 +931,7 @@ func TestDocumentHandlerIngestPropagatesServiceErrorCode(t *testing.T) {
fake := &fakeDocumentService{
ingestCode: common.CodeAuthenticationError,
- ingestErr: fmt.Errorf("No authorization."),
+ ingestErr: fmt.Errorf("no authorization"),
}
h := &DocumentHandler{
documentService: fake,
@@ -952,7 +952,7 @@ func TestDocumentHandlerIngestPropagatesServiceErrorCode(t *testing.T) {
if resp["code"] != float64(common.CodeAuthenticationError) {
t.Fatalf("expected auth error code, got %v", resp["code"])
}
- if resp["message"] != "No authorization." {
+ if resp["message"] != "no authorization" {
t.Fatalf("unexpected message: %v", resp["message"])
}
if resp["data"] != nil {
diff --git a/internal/handler/search.go b/internal/handler/search.go
index 5477c54d41..df4c371cbb 100644
--- a/internal/handler/search.go
+++ b/internal/handler/search.go
@@ -334,7 +334,7 @@ func (h *SearchHandler) UpdateSearch(c *gin.Context) {
errMsg := err.Error()
switch errMsg {
case "no authorization":
- common.ResponseWithCodeData(c, common.CodeAuthenticationError, false, "No authorization.")
+ common.ResponseWithCodeData(c, common.CodeAuthenticationError, false, "no authorization")
case "duplicated search name":
common.ResponseWithCodeData(c, common.CodeDataError, nil, "Duplicated search name.")
default:
diff --git a/internal/handler/tenant.go b/internal/handler/tenant.go
index d2a8af09b2..70bdbcd413 100644
--- a/internal/handler/tenant.go
+++ b/internal/handler/tenant.go
@@ -123,8 +123,6 @@ func (h *TenantHandler) GetDefaultModels(c *gin.Context) {
// @Summary Get Tenant Information
// @Description Get current user's tenant information (owner tenant)
// @Tags tenants
-// @Accept json
-// @Produce json
// @Security ApiKeyAuth
// @Success 200 {object} map[string]interface{}
// @Router /v1/user/tenant_info [get]
@@ -154,8 +152,6 @@ func (h *TenantHandler) TenantInfo(c *gin.Context) {
// @Summary Get Tenant List
// @Description Get all tenants that the current user belongs to
// @Tags tenants
-// @Accept json
-// @Produce json
// @Security ApiKeyAuth
// @Success 200 {object} map[string]interface{}
// @Router /v1/tenant/list [get]
@@ -165,8 +161,9 @@ func (h *TenantHandler) TenantList(c *gin.Context) {
common.ErrorWithCode(c, errorCode, errorMessage)
return
}
+ ctx := c.Request.Context()
- tenantList, err := h.tenantService.GetTenantList(user.ID)
+ tenantList, err := h.tenantService.GetTenantList(ctx, user.ID)
if err != nil {
common.ResponseWithCodeData(c, common.CodeExceptionError, false, err.Error())
return
@@ -263,7 +260,7 @@ func (h *TenantHandler) CreateChunkStore(c *gin.Context) {
ctx := c.Request.Context()
// Check authorization - user must have access to this kb
if !h.datasetService.Accessible(ctx, req.KBID, user.ID) {
- common.ResponseWithCodeData(c, common.CodeAuthenticationError, nil, "No authorization.")
+ common.ResponseWithCodeData(c, common.CodeAuthenticationError, nil, "no authorization")
return
}
@@ -311,7 +308,7 @@ func (h *TenantHandler) DeleteChunkStore(c *gin.Context) {
// Check authorization
if !h.datasetService.Accessible(ctx, req.KBID, user.ID) {
- common.ResponseWithCodeData(c, common.CodeAuthenticationError, nil, "No authorization.")
+ common.ResponseWithCodeData(c, common.CodeAuthenticationError, nil, "no authorization")
return
}
@@ -329,11 +326,9 @@ type InsertChunksFromFileRequest struct {
FilePath string `json:"file_path" binding:"required"`
}
-// @Summary Insert chunks into dataset from JSON file
+// InsertChunksFromFile @Summary Insert chunks into dataset from JSON file
// @Description Internal: Insert chunks into dataset table from a JSON file
// @Tags tenants
-// @Accept json
-// @Produce json
// @Security ApiKeyAuth
// @Param request body InsertChunksFromFileRequest true "insert chunks request"
// @Success 200 {object} map[string]interface{}
@@ -407,11 +402,9 @@ type InsertMetadataFromFileRequest struct {
FilePath string `json:"file_path" binding:"required"`
}
-// @Summary Insert document metadata from JSON file
+// InsertMetadataFromFile @Summary Insert document metadata from JSON file
// @Description Internal: Insert metadata into tenant's metadata table from a JSON file
// @Tags tenants
-// @Accept json
-// @Produce json
// @Security ApiKeyAuth
// @Param request body InsertMetadataFromFileRequest true "insert metadata request"
// @Success 200 {object} map[string]interface{}
@@ -435,10 +428,10 @@ func (h *TenantHandler) InsertMetadataFromFile(c *gin.Context) {
}
// Read the JSON file
- // JSON file path the operator configured (tenant import flow). The
+ // codeql[go/path-injection] False positive: req.FilePath is the
+ // path the operator configured (tenant import flow). The
// OS access check enforces permissions, and the handler is gated
// to admin/owner roles upstream.
- // codeql[go/path-injection] False positive: req.FilePath is the
data, err := os.ReadFile(req.FilePath)
if err != nil {
common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, "failed to read file: "+err.Error())
@@ -477,7 +470,6 @@ func (h *TenantHandler) InsertMetadataFromFile(c *gin.Context) {
// ListTenantMembers lists all non-owner members of a tenant.
// @Summary List tenant members
// @Tags tenants
-// @Produce json
// @Param tenant_id path string true "Tenant ID"
// @Router /api/v1/tenants/{tenant_id}/users [get]
func (h *TenantHandler) ListTenantMembers(c *gin.Context) {
@@ -493,7 +485,8 @@ func (h *TenantHandler) ListTenantMembers(c *gin.Context) {
return
}
- members, code, err := h.tenantService.ListMembers(user.ID, tenantID)
+ ctx := c.Request.Context()
+ members, code, err := h.tenantService.ListMembers(ctx, user.ID, tenantID)
if err != nil {
common.ResponseWithCodeData(c, code, nil, err.Error())
return
@@ -528,7 +521,8 @@ func (h *TenantHandler) AddTenantMember(c *gin.Context) {
return
}
- resp, code, err := h.tenantService.AddMember(user.ID, tenantID, &req)
+ ctx := c.Request.Context()
+ resp, code, err := h.tenantService.AddMember(ctx, user.ID, tenantID, &req)
if err != nil {
common.ResponseWithCodeData(c, code, nil, err.Error())
return
@@ -539,8 +533,6 @@ func (h *TenantHandler) AddTenantMember(c *gin.Context) {
// RemoveTenantMember removes a user from the tenant.
// @Summary Remove a user from a tenant
// @Tags tenants
-// @Accept json
-// @Produce json
// @Param tenant_id path string true "Tenant ID"
// @Param request body object true "Remove member request" SchemaExample({"user_id":"string"})
// @Router /api/v1/tenants/{tenant_id}/users [delete]
@@ -565,7 +557,8 @@ func (h *TenantHandler) RemoveTenantMember(c *gin.Context) {
return
}
- code, err := h.tenantService.RemoveMember(user.ID, tenantID, body.UserID)
+ ctx := c.Request.Context()
+ code, err := h.tenantService.RemoveMember(ctx, user.ID, tenantID, body.UserID)
if err != nil {
common.ResponseWithCodeData(c, code, nil, err.Error())
return
@@ -592,7 +585,8 @@ func (h *TenantHandler) AcceptTenantInvite(c *gin.Context) {
return
}
- code, err := h.tenantService.AcceptInvite(user.ID, tenantID)
+ ctx := c.Request.Context()
+ code, err := h.tenantService.AcceptInvite(ctx, user.ID, tenantID)
if err != nil {
common.ResponseWithCodeData(c, code, nil, err.Error())
return
diff --git a/internal/handler/user.go b/internal/handler/user.go
index 7c1ac6f412..223b41f7e0 100644
--- a/internal/handler/user.go
+++ b/internal/handler/user.go
@@ -50,8 +50,6 @@ func NewUserHandler(userService *service.UserService) *UserHandler {
// @Summary User Registration
// @Description Create new user
// @Tags users
-// @Accept json
-// @Produce json
// @Param request body service.RegisterRequest true "registration info"
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/users [post]
@@ -99,8 +97,6 @@ func (h *UserHandler) Register(c *gin.Context) {
// @Summary User Login
// @Description User login verification
// @Tags users
-// @Accept json
-// @Produce json
// @Param request body service.LoginRequest true "login info"
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/users/login [post]
@@ -134,7 +130,7 @@ func (h *UserHandler) Login(c *gin.Context) {
}
operationLog.ResourceName = req.Username
- user, code, err := h.userService.Login(&req)
+ user, code, err := h.userService.Login(ctx, &req)
if err != nil {
common.ResponseWithCodeData(c, code, false, err.Error())
operationLog.ErrorCode = uint16(code)
@@ -180,8 +176,6 @@ func (h *UserHandler) Login(c *gin.Context) {
// @Summary User Login by Email
// @Description User login verification using email
// @Tags users
-// @Accept json
-// @Produce json
// @Param request body service.EmailLoginRequest true "login info with email"
// @Success 200 {object} map[string]interface{}
// @Router /v1/user/login [post]
@@ -266,8 +260,6 @@ func (h *UserHandler) LoginByEmail(c *gin.Context) {
// @Summary Get User Info
// @Description Get user details by ID
// @Tags users
-// @Accept json
-// @Produce json
// @Param id path int true "user ID"
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/users/{id} [get]
@@ -293,8 +285,6 @@ func (h *UserHandler) GetUserByID(c *gin.Context) {
// @Summary User Logout
// @Description Logout user and invalidate access token
// @Tags users
-// @Accept json
-// @Produce json
// @Security ApiKeyAuth
// @Success 200 {object} map[string]interface{}
// @Router /v1/user/logout [post]
@@ -352,7 +342,7 @@ func (h *UserHandler) Logout(c *gin.Context) {
operationLog.UserID = user.ID
// Logout user
- code, err = h.userService.Logout(user)
+ code, err = h.userService.Logout(ctx, user)
if err != nil {
common.ResponseWithCodeData(c, code, false, err.Error())
operationLog.ErrorCode = uint16(code)
@@ -368,8 +358,6 @@ func (h *UserHandler) Logout(c *gin.Context) {
// @Summary Get User Profile
// @Description Get current user's profile information
// @Tags users
-// @Accept json
-// @Produce json
// @Security ApiKeyAuth
// @Success 200 {object} map[string]interface{}
// @Router /v1/user/info [get]
@@ -391,8 +379,6 @@ func (h *UserHandler) Info(c *gin.Context) {
// @Summary Update User Settings
// @Description Update current user's settings
// @Tags users
-// @Accept json
-// @Produce json
// @Security ApiKeyAuth
// @Param request body service.UpdateSettingsRequest true "user settings"
// @Success 200 {object} map[string]interface{}
@@ -430,8 +416,6 @@ func (h *UserHandler) Setting(c *gin.Context) {
// @Summary Change User Password
// @Description Change current user's password
// @Tags users
-// @Accept json
-// @Produce json
// @Security ApiKeyAuth
// @Param request body service.ChangePasswordRequest true "password change info"
// @Success 200 {object} map[string]interface{}
@@ -465,8 +449,6 @@ func (h *UserHandler) ChangePassword(c *gin.Context) {
// @Summary Get Login Channels
// @Description Get all supported OAuth authentication channels
// @Tags users
-// @Accept json
-// @Produce json
// @Success 200 {object} map[string]interface{}
// @Router /v1/user/login/channels [get]
func (h *UserHandler) GetLoginChannels(c *gin.Context) {
@@ -483,8 +465,6 @@ func (h *UserHandler) GetLoginChannels(c *gin.Context) {
// @Summary Set Tenant Info
// @Description Update tenant model configuration
// @Tags users
-// @Accept json
-// @Produce json
// @Security ApiKeyAuth
// @Param request body service.SetTenantInfoRequest true "tenant info"
// @Success 200 {object} map[string]interface{}
@@ -609,7 +589,8 @@ func (h *UserHandler) ForgotCaptcha(c *gin.Context) {
_ = c.ShouldBindJSON(&req)
}
- captchaID, captchaImage, errCode, err := h.userService.ForgotIssueCaptcha(req.Email)
+ ctx := c.Request.Context()
+ captchaID, captchaImage, errCode, err := h.userService.ForgotIssueCaptcha(ctx, req.Email)
if err != nil {
common.ResponseWithCodeData(c, errCode, false, err.Error())
return
@@ -632,8 +613,6 @@ type forgotSendOTPRequest struct {
// mints a one-time code, stores a salted hash in Redis (5 min TTL,
// attempt cap, resend cooldown), and emails the OTP to the user.
// @Tags auth
-// @Accept json
-// @Produce json
// @Param request body forgotSendOTPRequest true "email + captcha_id + captcha"
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/auth/password/forgot/otp [post]
@@ -643,7 +622,8 @@ func (h *UserHandler) ForgotSendOTP(c *gin.Context) {
common.ResponseWithCodeData(c, common.CodeArgumentError, false, err.Error())
return
}
- errCode, err := h.userService.ForgotSendOTP(req.Email, req.CaptchaID, req.Captcha)
+ ctx := c.Request.Context()
+ errCode, err := h.userService.ForgotSendOTP(ctx, req.Email, req.CaptchaID, req.Captcha)
if err != nil {
common.ResponseWithCodeData(c, errCode, false, err.Error())
return
@@ -662,8 +642,6 @@ type forgotVerifyOTPRequest struct {
// verified flag the reset endpoint will gate on. Wrong-OTP attempts
// are counted and a 30-minute lockout kicks in at the limit.
// @Tags auth
-// @Accept json
-// @Produce json
// @Param request body forgotVerifyOTPRequest true "email + otp"
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/auth/password/forgot/otp/verify [post]
@@ -673,7 +651,8 @@ func (h *UserHandler) ForgotVerifyOTP(c *gin.Context) {
common.ResponseWithCodeData(c, common.CodeArgumentError, false, err.Error())
return
}
- errCode, err := h.userService.ForgotVerifyOTP(req.Email, req.OTP)
+ ctx := c.Request.Context()
+ errCode, err := h.userService.ForgotVerifyOTP(ctx, req.Email, req.OTP)
if err != nil {
common.ResponseWithCodeData(c, errCode, false, err.Error())
return
@@ -700,7 +679,7 @@ func (h *UserHandler) ForgotResetPassword(c *gin.Context) {
return
}
- user, code, err := h.userService.ForgotResetPassword(&req)
+ user, code, err := h.userService.ForgotResetPassword(ctx, &req)
if err != nil {
common.ResponseWithCodeData(c, code, false, err.Error())
return
diff --git a/internal/ingestion/task/pipeline_executor.go b/internal/ingestion/task/pipeline_executor.go
index fc509d0bc3..07d11d2eb8 100644
--- a/internal/ingestion/task/pipeline_executor.go
+++ b/internal/ingestion/task/pipeline_executor.go
@@ -222,7 +222,7 @@ func (s *PipelineExecutor) processOutput(ctx context.Context, pipelineOutput map
}
}
- if err := s.indexWriter.Write(ctx, chunks); err != nil {
+ if err = s.indexWriter.Write(ctx, chunks); err != nil {
return nil, err
}
@@ -288,7 +288,7 @@ func (s *PipelineExecutor) loadDSLFromCanvas(ctx context.Context, canvasID strin
if canvasID == "" {
return "", "", fmt.Errorf("pipeline executor: empty canvas id")
}
- canvas, err := dao.NewUserCanvasDAO().GetByID(canvasID)
+ canvas, err := dao.NewUserCanvasDAO().GetByID(ctx, dao.DB, canvasID)
if err != nil {
return "", "", fmt.Errorf("load canvas %s: %w", canvasID, err)
}
diff --git a/internal/ingestion/task/pipeline_run_test.go b/internal/ingestion/task/pipeline_run_test.go
index 8ae1ae202a..a548f1aaa4 100644
--- a/internal/ingestion/task/pipeline_run_test.go
+++ b/internal/ingestion/task/pipeline_run_test.go
@@ -17,7 +17,6 @@
package task
import (
- "context"
"encoding/json"
"strings"
"testing"
@@ -30,16 +29,17 @@ import (
func TestPipelineExecutor_DefaultLoadDSL_UsesUserCanvas(t *testing.T) {
cleanup := setupPipelineExecutorTestDB(t)
defer cleanup()
+ ctx := t.Context()
dslMap := entity.JSONMap{"dsl": map[string]any{"graph": map[string]any{"nodes": []any{}, "edges": []any{}}}}
title := "title 1"
- if err := dao.NewUserCanvasDAO().Create(&entity.UserCanvas{Title: &title, ID: "canvas-1", UserID: "u1", Permission: "me", CanvasCategory: "agent_canvas", DSL: dslMap}); err != nil {
+ if err := dao.NewUserCanvasDAO().Create(ctx, dao.DB, &entity.UserCanvas{Title: &title, ID: "canvas-1", UserID: "u1", Permission: "me", CanvasCategory: "agent_canvas", DSL: dslMap}); err != nil {
t.Fatalf("create user canvas: %v", err)
}
- ctx := makeTaskCtx()
- svc := mustNewPipelineExecutor(t, ctx, "canvas-1", 0)
- gotDSL, correctedID, err := svc.loadDSLFunc(context.Background(), "canvas-1")
+ taskCtx := makeTaskCtx()
+ svc := mustNewPipelineExecutor(t, taskCtx, "canvas-1", 0)
+ gotDSL, correctedID, err := svc.loadDSLFunc(ctx, "canvas-1")
if err != nil {
t.Fatalf("loadDSLFunc: %v", err)
}
@@ -47,7 +47,7 @@ func TestPipelineExecutor_DefaultLoadDSL_UsesUserCanvas(t *testing.T) {
t.Fatalf("correctedID = %q, want canvas-1", correctedID)
}
var decoded map[string]any
- if err := json.Unmarshal([]byte(gotDSL), &decoded); err != nil {
+ if err = json.Unmarshal([]byte(gotDSL), &decoded); err != nil {
t.Fatalf("unmarshal dsl: %v", err)
}
if _, ok := decoded["dsl"].(map[string]any); !ok {
diff --git a/internal/service/agent.go b/internal/service/agent.go
index 79a630488f..9b648bf658 100644
--- a/internal/service/agent.go
+++ b/internal/service/agent.go
@@ -454,9 +454,9 @@ func toAgentItem(c *dao.UserCanvasListItem) *AgentItem {
// ListAgents returns agent canvases visible to userID.
// Mirrors Python agent_api.list_agents — validates owner_ids against joined tenants,
// then delegates to the DAO.
-func (s *AgentService) ListAgents(userID string, keywords string, page, pageSize int, orderBy string, desc bool, ownerIDs []string, canvasCategory, canvasType string, tags []string) (*ListAgentsResponse, common.ErrorCode, error) {
+func (s *AgentService) ListAgents(ctx context.Context, userID string, keywords string, page, pageSize int, orderBy string, desc bool, ownerIDs []string, canvasCategory, canvasType string, tags []string) (*ListAgentsResponse, common.ErrorCode, error) {
// Build the set of tenant IDs the user is authorized to query.
- tenantIDs, err := s.userTenantDAO.GetTenantIDsByUserID(userID)
+ tenantIDs, err := s.userTenantDAO.GetTenantIDsByUserID(ctx, dao.DB, userID)
if err != nil {
return nil, common.CodeServerError, fmt.Errorf("failed to get tenant IDs: %w", err)
}
@@ -482,6 +482,8 @@ func (s *AgentService) ListAgents(userID string, keywords string, page, pageSize
}
canvases, total, err := s.canvasDAO.ListByTenantIDs(
+ ctx,
+ dao.DB,
effectiveOwnerIDs,
userID,
page,
@@ -542,7 +544,7 @@ func (s *AgentService) CreateAgent(ctx context.Context, req *CreateAgentRequest)
req.CanvasCategory = "agent_canvas"
}
- if existing, err := s.canvasDAO.GetByUserAndTitle(req.UserID, title, req.CanvasCategory); err != nil {
+ if existing, err := s.canvasDAO.GetByUserAndTitle(ctx, dao.DB, req.UserID, title, req.CanvasCategory); err != nil {
return nil, common.CodeServerError, fmt.Errorf("check duplicate title: %w", err)
} else if existing != nil {
return nil, common.CodeDataError, agentTitleAlreadyExistsError(title)
@@ -561,7 +563,7 @@ func (s *AgentService) CreateAgent(ctx context.Context, req *CreateAgentRequest)
CanvasCategory: req.CanvasCategory,
DSL: req.DSL,
}
- if err := s.canvasDAO.Create(row); err != nil {
+ if err := s.canvasDAO.Create(ctx, dao.DB, row); err != nil {
if dao.IsDuplicateKeyErr(err) {
return nil, common.CodeDataError, agentTitleAlreadyExistsError(title)
}
@@ -625,14 +627,14 @@ func (s *AgentService) loadCanvasForUser(ctx context.Context, userID, canvasID s
if userID == "" {
return nil, dao.ErrUserCanvasNotFound
}
- tenants, err := s.userTenantDAO.GetTenantIDsByUserID(userID)
+ tenants, err := s.userTenantDAO.GetTenantIDsByUserID(ctx, dao.DB, userID)
if err != nil {
if errors.Is(err, dao.ErrUserCanvasNotFound) {
return nil, err
}
return nil, fmt.Errorf("tenants for user %s: %w: %w", userID, err, ErrAgentStorageError)
}
- row, err := s.canvasDAO.GetByIDForUser(canvasID, userID, tenants)
+ row, err := s.canvasDAO.GetByIDForUser(ctx, dao.DB, canvasID, userID, tenants)
if err != nil {
if errors.Is(err, dao.ErrUserCanvasNotFound) {
return nil, err
@@ -681,7 +683,7 @@ func (s *AgentService) UpdateAgent(ctx context.Context, userID, canvasID string,
}
if title, ok := updatedAgentTitle(canvasInstance, updates); ok {
canvasCategory := updatedAgentCanvasCategory(canvasInstance, updates)
- if existing, err := s.canvasDAO.GetByUserAndTitle(userID, title, canvasCategory); err != nil {
+ if existing, err := s.canvasDAO.GetByUserAndTitle(ctx, dao.DB, userID, title, canvasCategory); err != nil {
return fmt.Errorf("check duplicate title: %w", err)
} else if existing != nil && existing.ID != canvasID {
return agentTitleAlreadyExistsError(title)
@@ -699,7 +701,7 @@ func (s *AgentService) UpdateAgent(ctx context.Context, userID, canvasID string,
updates["dsl"] = entity.JSONMap(dslpkg.NormalizeForCanvas(dslMap))
}
- _, err = s.canvasDAO.UpdateFields(canvasID, updates)
+ _, err = s.canvasDAO.UpdateFields(ctx, dao.DB, canvasID, updates)
if err != nil {
if dao.IsDuplicateKeyErr(err) {
if title, ok := updatedAgentTitle(canvasInstance, updates); ok {
@@ -756,7 +758,7 @@ func (s *AgentService) ResetAgent(ctx context.Context, userID, canvasID string)
// reset that left the legacy short-form DSL intact.
row.DSL = dslpkg.NormalizeForCanvas(reset)
row.Release = false
- if err := s.canvasDAO.Update(row); err != nil {
+ if err = s.canvasDAO.Update(ctx, dao.DB, row); err != nil {
return nil, fmt.Errorf("reset agent %s: %w", canvasID, err)
}
return row.DSL, nil
@@ -774,7 +776,7 @@ func (s *AgentService) ResetAgent(ctx context.Context, userID, canvasID string)
// UserCanvasService.query(user_id=..., id=...) and conflates those two
// cases into one OPERATING_ERROR response.
func (s *AgentService) DeleteAgent(ctx context.Context, userID, canvasID string) error {
- row, err := s.canvasDAO.GetByID(canvasID)
+ row, err := s.canvasDAO.GetByID(ctx, dao.DB, canvasID)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return ErrAgentNotOwner
@@ -784,11 +786,11 @@ func (s *AgentService) DeleteAgent(ctx context.Context, userID, canvasID string)
if row.UserID != userID {
return ErrAgentNotOwner
}
- return dao.DB.Transaction(func(tx *gorm.DB) error {
- if _, err = s.versionDAO.DeleteByCanvasIDTx(tx, canvasID); err != nil {
+ return dao.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ if _, err = s.versionDAO.DeleteByCanvasIDTx(ctx, tx, canvasID); err != nil {
return fmt.Errorf("delete agent: cascade versions: %w", err)
}
- if err = s.canvasDAO.DeleteTx(tx, canvasID); err != nil {
+ if err = s.canvasDAO.DeleteTx(ctx, tx, canvasID); err != nil {
return fmt.Errorf("delete agent %s: %w", canvasID, err)
}
return nil
@@ -833,11 +835,11 @@ func (s *AgentService) PublishAgent(ctx context.Context, userID, canvasID string
}
opts := s.saveOrReplaceVersionOptions(ctx, userID, canvasID, dsl, titleStr, description, true)
var row *entity.UserCanvasVersion
- if err = dao.DB.Transaction(func(tx *gorm.DB) error {
- if err = s.canvasDAO.UpdateTx(tx, canvasInstance); err != nil {
+ if err = dao.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ if err = s.canvasDAO.UpdateTx(ctx, tx, canvasInstance); err != nil {
return fmt.Errorf("publish agent %s: update parent: %w", canvasID, err)
}
- saved, err := s.versionDAO.SaveOrReplaceLatestTx(tx, opts)
+ saved, err := s.versionDAO.SaveOrReplaceLatestTx(ctx, tx, opts)
if err != nil {
return fmt.Errorf("publish agent %s: save version: %w", canvasID, err)
}
@@ -850,11 +852,11 @@ func (s *AgentService) PublishAgent(ctx context.Context, userID, canvasID string
}
func (s *AgentService) saveOrReplaceVersion(ctx context.Context, userID, canvasID string, dsl entity.JSONMap, title string, description *string, release bool) (*entity.UserCanvasVersion, error) {
- return s.versionDAO.SaveOrReplaceLatest(s.saveOrReplaceVersionOptions(ctx, userID, canvasID, dsl, title, description, release))
+ return s.versionDAO.SaveOrReplaceLatest(ctx, dao.DB, s.saveOrReplaceVersionOptions(ctx, userID, canvasID, dsl, title, description, release))
}
func (s *AgentService) saveOrReplaceVersionOptions(ctx context.Context, userID, canvasID string, dsl entity.JSONMap, title string, description *string, release bool) dao.SaveOrReplaceLatestVersionOptions {
- nickname, err := s.userDAO.GetNicknameByID(ctx, userID)
+ nickname, err := s.userDAO.GetNicknameByID(ctx, dao.DB, userID)
if err != nil || strings.TrimSpace(nickname) == "" {
nickname = userID
}
@@ -896,7 +898,7 @@ func (s *AgentService) ListVersions(ctx context.Context, userID, canvasID string
if _, err := s.loadCanvasForUser(ctx, userID, canvasID); err != nil {
return nil, err
}
- return s.versionDAO.ListByCanvasID(canvasID)
+ return s.versionDAO.ListByCanvasID(ctx, dao.DB, canvasID)
}
// GetVersion returns a single version of a canvas the user can see.
@@ -911,7 +913,7 @@ func (s *AgentService) GetVersion(ctx context.Context, userID, canvasID, version
if _, err := s.loadCanvasForUser(ctx, userID, canvasID); err != nil {
return nil, err
}
- row, err := s.versionDAO.GetByID(versionID)
+ row, err := s.versionDAO.GetByID(ctx, dao.DB, versionID)
if err != nil {
return nil, err
}
@@ -932,7 +934,7 @@ func (s *AgentService) DeleteVersion(ctx context.Context, userID, canvasID, vers
if _, err := s.loadCanvasForUser(ctx, userID, canvasID); err != nil {
return err
}
- row, err := s.versionDAO.GetByID(versionID)
+ row, err := s.versionDAO.GetByID(ctx, dao.DB, versionID)
if err != nil {
return err
}
@@ -940,7 +942,7 @@ func (s *AgentService) DeleteVersion(ctx context.Context, userID, canvasID, vers
return dao.ErrUserCanvasVersionNotFound
}
return dao.DB.Transaction(func(tx *gorm.DB) error {
- return s.versionDAO.DeleteTx(tx, versionID)
+ return s.versionDAO.DeleteTx(ctx, tx, versionID)
})
}
@@ -1117,7 +1119,7 @@ func (s *AgentService) RunAgent(ctx context.Context, userID, canvasID, sessionID
dsl map[string]any
)
if version != "" {
- row, err := s.versionDAO.GetByID(version)
+ row, err := s.versionDAO.GetByID(ctx, dao.DB, version)
if err != nil {
if errors.Is(err, dao.ErrUserCanvasVersionNotFound) {
return nil, fmt.Errorf("RunAgent: load version %q: %w", version, err)
@@ -1142,7 +1144,7 @@ func (s *AgentService) RunAgent(ctx context.Context, userID, canvasID, sessionID
versionRow = row
}
if versionRow == nil {
- row, lerr := s.versionDAO.GetLatest(canvasID)
+ row, lerr := s.versionDAO.GetLatest(ctx, dao.DB, canvasID)
switch {
case lerr == nil:
versionRow = row
@@ -1236,7 +1238,7 @@ func (s *AgentService) RunAgent(ctx context.Context, userID, canvasID, sessionID
// Preserve the historical RunTracker tenant dimension separately.
// Existing tests and log filters expect the joined tenant id in the
// run hash, but runtime state must keep tenant_id=userID.
- if tenantIDs, terr := s.userTenantDAO.GetTenantIDsByUserID(userID); terr == nil && len(tenantIDs) > 0 {
+ if tenantIDs, terr := s.userTenantDAO.GetTenantIDsByUserID(ctx, dao.DB, userID); terr == nil && len(tenantIDs) > 0 {
root["run_tenant_id"] = tenantIDs[0]
} else if terr != nil {
common.Warn("service: RunAgent userTenantDAO.GetTenantIDsByUserID (best-effort, run tracker tenant not populated)",
diff --git a/internal/service/agent_sessions.go b/internal/service/agent_sessions.go
index 6c113e0d96..e80cf3987d 100644
--- a/internal/service/agent_sessions.go
+++ b/internal/service/agent_sessions.go
@@ -27,8 +27,6 @@ import (
"strings"
"time"
- "gorm.io/gorm"
-
"ragflow/internal/common"
"ragflow/internal/dao"
"ragflow/internal/entity"
@@ -74,8 +72,8 @@ type DeleteAgentSessionsResponse struct {
// CheckCanvasAccess returns true when the user is the canvas owner or
// holds team-level permission for the owner's tenant.
-func (s *AgentService) CheckCanvasAccess(userID, canvasID string) (bool, error) {
- canvas, err := s.canvasDAO.GetByID(canvasID)
+func (s *AgentService) CheckCanvasAccess(ctx context.Context, userID, canvasID string) (bool, error) {
+ canvas, err := s.canvasDAO.GetByID(ctx, dao.DB, canvasID)
if err != nil {
return false, err
}
@@ -85,7 +83,7 @@ func (s *AgentService) CheckCanvasAccess(userID, canvasID string) (bool, error)
if canvas.Permission != string(entity.TenantPermissionTeam) {
return false, nil
}
- tenantIDs, err := s.userTenantDAO.GetTenantIDsByUserID(userID)
+ tenantIDs, err := s.userTenantDAO.GetTenantIDsByUserID(ctx, dao.DB, userID)
if err != nil {
return false, err
}
@@ -317,7 +315,7 @@ func (s *AgentService) ListAgentSessions(ctx context.Context, userID, tenantID,
return nil, common.CodeArgumentError, errors.New("agent_id is required")
}
- ok, err := s.CheckCanvasAccess(userID, agentID)
+ ok, err := s.CheckCanvasAccess(ctx, userID, agentID)
if err != nil {
// The Python agent API folds "canvas does not exist" into
// the same 103 access envelope as a permission mismatch
@@ -382,7 +380,7 @@ func (s *AgentService) GetAgentSession(ctx context.Context, userID, agentID, ses
if sessionID == "" {
return nil, common.CodeArgumentError, fmt.Errorf("session_id is required")
}
- ok, err := s.CheckCanvasAccess(userID, agentID)
+ ok, err := s.CheckCanvasAccess(ctx, userID, agentID)
if err != nil {
if errors.Is(err, dao.ErrUserCanvasNotFound) {
return nil, common.CodeOperatingError, errors.New("agent not found or no permission")
@@ -408,7 +406,7 @@ func (s *AgentService) DeleteAgentSessionItem(ctx context.Context, userID, agent
if sessionID == "" {
return false, common.CodeArgumentError, errors.New("session_id is required")
}
- ok, err := s.CheckCanvasAccess(userID, agentID)
+ ok, err := s.CheckCanvasAccess(ctx, userID, agentID)
if err != nil {
if errors.Is(err, dao.ErrUserCanvasNotFound) {
return false, common.CodeOperatingError, errors.New("agent not found or no permission")
@@ -441,7 +439,7 @@ func (s *AgentService) DeleteAgentSessions(ctx context.Context, userID, agentID
// not be available to team members even when the canvas has team
// permission. CheckCanvasAccess (used elsewhere) would also allow team
// access, which is too permissive for this operation.
- canvas, err := s.canvasDAO.GetByID(agentID)
+ canvas, err := s.canvasDAO.GetByID(ctx, dao.DB, agentID)
if err != nil || canvas == nil || canvas.UserID != userID {
return nil, common.CodeDataError, fmt.Errorf("you don't own the agent %s", agentID)
}
@@ -480,7 +478,7 @@ func (s *AgentService) DeleteAgentSessions(ctx context.Context, userID, agentID
continue
}
- if _, err := s.api4ConversationDAO.DeleteBySessionIDAndAgentID(ctx, dao.DB, sessionID, agentID); err != nil {
+ if _, err = s.api4ConversationDAO.DeleteBySessionIDAndAgentID(ctx, dao.DB, sessionID, agentID); err != nil {
return nil, common.CodeServerError, err
}
successCount++
@@ -513,8 +511,8 @@ func (s *AgentService) DeleteAgentSessions(ctx context.Context, userID, agentID
}
// ListAgentTags list agent tags
-func (s *AgentService) ListAgentTags(userID, canvasCategory string) ([]AgentTagCount, common.ErrorCode, error) {
- tenantIDs, err := s.userTenantDAO.GetTenantIDsByUserID(userID)
+func (s *AgentService) ListAgentTags(ctx context.Context, userID, canvasCategory string) ([]AgentTagCount, common.ErrorCode, error) {
+ tenantIDs, err := s.userTenantDAO.GetTenantIDsByUserID(ctx, dao.DB, userID)
if err != nil {
return nil, common.CodeServerError, err
}
@@ -529,7 +527,7 @@ func (s *AgentService) ListAgentTags(userID, canvasCategory string) ([]AgentTagC
ownerIDs = append(ownerIDs, id)
}
- counts, err := s.canvasDAO.ListTags(ownerIDs, userID, canvasCategory)
+ counts, err := s.canvasDAO.ListTags(ctx, dao.DB, ownerIDs, userID, canvasCategory)
if err != nil {
return nil, common.CodeServerError, err
}
@@ -623,8 +621,8 @@ func truncateRunes(value string, maxLen int) string {
}
// UpdateAgentTags normalises tags and persists them on a single canvas.
-func (s *AgentService) UpdateAgentTags(userID, canvasID string, tags interface{}) (bool, common.ErrorCode, error) {
- ok, err := s.CheckCanvasAccess(userID, canvasID)
+func (s *AgentService) UpdateAgentTags(ctx context.Context, userID, canvasID string, tags interface{}) (bool, common.ErrorCode, error) {
+ ok, err := s.CheckCanvasAccess(ctx, userID, canvasID)
if err != nil {
if errors.Is(err, dao.ErrUserCanvasNotFound) {
return false, common.CodeOperatingError, errors.New("agent not found or no permission")
@@ -639,12 +637,12 @@ func (s *AgentService) UpdateAgentTags(userID, canvasID string, tags interface{}
if nErr != nil {
return false, common.CodeBadRequest, nErr
}
- rows, err := s.canvasDAO.UpdateTags(canvasID, normalized)
+ rows, err := s.canvasDAO.UpdateTags(ctx, dao.DB, canvasID, normalized)
if err != nil {
return false, common.CodeServerError, fmt.Errorf("failed to update agent tags: %w", err)
}
if rows == 0 {
- if _, getErr := s.canvasDAO.GetByCanvasID(canvasID); getErr != nil {
+ if _, getErr := s.canvasDAO.GetByCanvasID(ctx, dao.DB, canvasID); getErr != nil {
return false, common.CodeOperatingError, errors.New("agent not found or no permission")
}
return true, common.CodeSuccess, nil
@@ -698,8 +696,11 @@ func (s *AgentService) CreateAgentSession(ctx context.Context, req *CreateAgentS
return nil, common.CodeArgumentError, errors.New("create agent session: user_id is required")
}
- ok, err := s.CheckCanvasAccess(req.UserID, req.AgentID)
+ ok, err := s.CheckCanvasAccess(ctx, req.UserID, req.AgentID)
if err != nil {
+ if errors.Is(err, dao.ErrUserCanvasNotFound) {
+ return nil, common.CodeOperatingError, errors.New("agent not found or no permission")
+ }
return nil, common.CodeServerError, fmt.Errorf("check canvas access: %w", err)
}
if !ok {
@@ -717,9 +718,9 @@ func (s *AgentService) CreateAgentSession(ctx context.Context, req *CreateAgentS
_ = json.Unmarshal(req.DSL, &dsl)
}
if len(dsl) == 0 {
- canvas, gErr := s.canvasDAO.GetByID(req.AgentID)
+ canvas, gErr := s.canvasDAO.GetByID(ctx, dao.DB, req.AgentID)
if gErr != nil {
- if errors.Is(gErr, gorm.ErrRecordNotFound) {
+ if errors.Is(gErr, dao.ErrUserCanvasNotFound) {
return nil, common.CodeOperatingError, errors.New("agent not found or no permission")
}
return nil, common.CodeServerError, fmt.Errorf("load canvas dsl: %w", gErr)
diff --git a/internal/service/agent_test.go b/internal/service/agent_test.go
index c442539bc7..46821d8dcb 100644
--- a/internal/service/agent_test.go
+++ b/internal/service/agent_test.go
@@ -17,7 +17,6 @@
package service
import (
- "context"
"encoding/json"
"errors"
"net/netip"
@@ -307,8 +306,9 @@ func TestListVersions_Success(t *testing.T) {
},
})
+ ctx := t.Context()
svc := NewAgentService()
- versions, err := svc.ListVersions(context.Background(), "user-1", "canvas-1")
+ versions, err := svc.ListVersions(ctx, "user-1", "canvas-1")
if err != nil {
t.Fatalf("ListVersions failed: %v", err)
}
@@ -351,8 +351,9 @@ func TestListVersions_Empty(t *testing.T) {
Title: sptr("Empty Agent"),
})
+ ctx := t.Context()
svc := NewAgentService()
- versions, err := svc.ListVersions(context.Background(), "user-1", "canvas-empty")
+ versions, err := svc.ListVersions(ctx, "user-1", "canvas-empty")
if err != nil {
t.Fatalf("ListVersions failed: %v", err)
}
@@ -418,8 +419,9 @@ func TestGetVersion_Success(t *testing.T) {
DSL: entity.JSONMap{"model": "gpt-4"},
})
+ ctx := t.Context()
svc := NewAgentService()
- v, err := svc.GetVersion(context.Background(), "user-1", "canvas-1", "v1")
+ v, err := svc.GetVersion(ctx, "user-1", "canvas-1", "v1")
if err != nil {
t.Fatalf("GetVersion failed: %v", err)
}
@@ -451,8 +453,9 @@ func TestGetVersion_WrongCanvas(t *testing.T) {
Title: sptr("version-1"),
})
+ ctx := t.Context()
svc := NewAgentService()
- _, err := svc.GetVersion(context.Background(), "user-other", "canvas-other", "v1")
+ _, err := svc.GetVersion(ctx, "user-other", "canvas-other", "v1")
if err == nil {
t.Error("expected error for version belonging to another canvas")
}
@@ -475,8 +478,9 @@ func TestGetVersion_NotFound(t *testing.T) {
dao.DB = testDB
t.Cleanup(func() { dao.DB = orig })
+ ctx := t.Context()
svc := NewAgentService()
- _, err := svc.GetVersion(context.Background(), "user-1", "canvas-1", "non-existent")
+ _, err := svc.GetVersion(ctx, "user-1", "canvas-1", "non-existent")
if err == nil {
t.Error("expected error for non-existent version")
}
@@ -529,9 +533,10 @@ func TestRunAgent_VersionBelongsToOtherCanvas(t *testing.T) {
DSL: entity.JSONMap{"components": map[string]any{}},
})
+ ctx := t.Context()
svc := NewAgentService()
_, err := svc.RunAgent(
- context.Background(),
+ ctx,
"user-1",
"canvas-1", // we're running canvas-1…
"", // session ID auto-generated
@@ -575,9 +580,10 @@ func TestRunAgent_VersionNotFound(t *testing.T) {
Title: sptr("Canvas 1"),
})
+ ctx := t.Context()
svc := NewAgentService()
_, err := svc.RunAgent(
- context.Background(),
+ ctx,
"user-1",
"canvas-1",
"",
@@ -632,9 +638,10 @@ func TestRunAgent_NoVersionPublishedPlaceholder(t *testing.T) {
Title: sptr("Canvas With No Version"),
})
+ ctx := t.Context()
svc := NewAgentService()
events, err := svc.RunAgent(
- context.Background(),
+ ctx,
"user-1",
"canvas-empty",
"test-session",
@@ -741,9 +748,10 @@ func TestRunAgent_StorageErrorFromCanvasAccess(t *testing.T) {
t.Fatalf("failed to close sql.DB: %v", cErr)
}
+ ctx := t.Context()
svc := NewAgentService()
_, err := svc.RunAgent(
- context.Background(),
+ ctx,
"user-1",
"canvas-1",
"",
@@ -795,8 +803,9 @@ func TestLoadCanvasForUser_StorageErrorWrap(t *testing.T) {
t.Fatalf("failed to close sql.DB: %v", cErr)
}
+ ctx := t.Context()
svc := NewAgentService()
- _, err := svc.loadCanvasForUser(context.Background(), "user-1", "canvas-1")
+ _, err := svc.loadCanvasForUser(ctx, "user-1", "canvas-1")
if err == nil {
t.Fatal("expected storage error from closed DB")
}
@@ -991,14 +1000,14 @@ func TestDeleteAgentSessionItemServiceDeletesMatchingSession(t *testing.T) {
}
var count int64
- if err = dao.DB.Model(&entity.API4Conversation{}).Where("id = ?", "session-1").Count(&count).Error; err != nil {
+ if err = dao.DB.WithContext(ctx).Model(&entity.API4Conversation{}).Where("id = ?", "session-1").Count(&count).Error; err != nil {
t.Fatalf("failed to count deleted session: %v", err)
}
if count != 0 {
t.Fatalf("expected session-1 to be deleted, count=%d", count)
}
- if err = dao.DB.Model(&entity.API4Conversation{}).Where("id = ?", "session-other").Count(&count).Error; err != nil {
+ if err = dao.DB.WithContext(ctx).Model(&entity.API4Conversation{}).Where("id = ?", "session-other").Count(&count).Error; err != nil {
t.Fatalf("failed to count other session: %v", err)
}
if count != 1 {
@@ -1025,7 +1034,7 @@ func TestDeleteAgentSessionItemServiceNoopForSessionFromAnotherAgent(t *testing.
}
var count int64
- if err := dao.DB.Model(&entity.API4Conversation{}).Where("id = ?", "session-other").Count(&count).Error; err != nil {
+ if err = dao.DB.WithContext(ctx).Model(&entity.API4Conversation{}).Where("id = ?", "session-other").Count(&count).Error; err != nil {
t.Fatalf("failed to count other session: %v", err)
}
if count != 1 {
@@ -1057,7 +1066,7 @@ func TestDeleteAgentSessionsServiceDeleteAll(t *testing.T) {
}
var ownCount int64
- if err = dao.DB.Model(&entity.API4Conversation{}).Where("dialog_id = ?", "canvas-1").Count(&ownCount).Error; err != nil {
+ if err = dao.DB.WithContext(ctx).Model(&entity.API4Conversation{}).Where("dialog_id = ?", "canvas-1").Count(&ownCount).Error; err != nil {
t.Fatalf("failed to count own sessions: %v", err)
}
if ownCount != 0 {
@@ -1065,7 +1074,7 @@ func TestDeleteAgentSessionsServiceDeleteAll(t *testing.T) {
}
var otherCount int64
- if err = dao.DB.Model(&entity.API4Conversation{}).Where("id = ?", "session-other").Count(&otherCount).Error; err != nil {
+ if err = dao.DB.WithContext(ctx).Model(&entity.API4Conversation{}).Where("id = ?", "session-other").Count(&otherCount).Error; err != nil {
t.Fatalf("failed to count other session: %v", err)
}
if otherCount != 1 {
@@ -1098,7 +1107,7 @@ func TestDeleteAgentSessionsServiceDuplicateIDsPartial(t *testing.T) {
}
var count int64
- if err = dao.DB.Model(&entity.API4Conversation{}).Where("id = ?", "session-1").Count(&count).Error; err != nil {
+ if err = dao.DB.WithContext(ctx).Model(&entity.API4Conversation{}).Where("id = ?", "session-1").Count(&count).Error; err != nil {
t.Fatalf("failed to count deleted session: %v", err)
}
if count != 0 {
@@ -1146,7 +1155,7 @@ func TestDeleteAgentSessionsServiceRequiresOwner(t *testing.T) {
}
var count int64
- if err = dao.DB.Model(&entity.API4Conversation{}).Where("id = ?", "session-1").Count(&count).Error; err != nil {
+ if err = dao.DB.WithContext(ctx).Model(&entity.API4Conversation{}).Where("id = ?", "session-1").Count(&count).Error; err != nil {
t.Fatalf("failed to count session: %v", err)
}
if count != 1 {
@@ -1159,7 +1168,8 @@ func TestUpdateAgentTagsServiceSuccess(t *testing.T) {
createAgentSessionTestCanvas(t, "canvas-1", "user-1")
- ok, code, err := NewAgentService().UpdateAgentTags("user-1", "canvas-1", []interface{}{"alpha", "beta", "alpha", "with,comma"})
+ ctx := t.Context()
+ ok, code, err := NewAgentService().UpdateAgentTags(ctx, "user-1", "canvas-1", []interface{}{"alpha", "beta", "alpha", "with,comma"})
if err != nil {
t.Fatalf("UpdateAgentTags failed: %v", err)
}
@@ -1170,7 +1180,7 @@ func TestUpdateAgentTagsServiceSuccess(t *testing.T) {
t.Fatal("expected update to succeed")
}
- canvas, err := dao.NewUserCanvasDAO().GetByID("canvas-1")
+ canvas, err := dao.NewUserCanvasDAO().GetByID(ctx, dao.DB, "canvas-1")
if err != nil {
t.Fatalf("failed to get canvas: %v", err)
}
@@ -1184,7 +1194,8 @@ func TestUpdateAgentTagsServiceInvalidPayload(t *testing.T) {
createAgentSessionTestCanvas(t, "canvas-1", "user-1")
- ok, code, err := NewAgentService().UpdateAgentTags("user-1", "canvas-1", map[string]string{"tag": "alpha"})
+ ctx := t.Context()
+ ok, code, err := NewAgentService().UpdateAgentTags(ctx, "user-1", "canvas-1", map[string]string{"tag": "alpha"})
if err == nil {
t.Fatal("expected invalid tags error")
}
@@ -1195,7 +1206,7 @@ func TestUpdateAgentTagsServiceInvalidPayload(t *testing.T) {
t.Fatal("expected update to fail")
}
- canvas, err := dao.NewUserCanvasDAO().GetByID("canvas-1")
+ canvas, err := dao.NewUserCanvasDAO().GetByID(ctx, dao.DB, "canvas-1")
if err != nil {
t.Fatalf("failed to get canvas: %v", err)
}
@@ -1209,7 +1220,8 @@ func TestUpdateAgentTagsServiceNoPermission(t *testing.T) {
createAgentSessionTestCanvas(t, "canvas-1", "user-2")
- ok, code, err := NewAgentService().UpdateAgentTags("user-1", "canvas-1", []string{"alpha"})
+ ctx := t.Context()
+ ok, code, err := NewAgentService().UpdateAgentTags(ctx, "user-1", "canvas-1", []string{"alpha"})
if err == nil {
t.Fatal("expected permission error")
}
@@ -1220,7 +1232,7 @@ func TestUpdateAgentTagsServiceNoPermission(t *testing.T) {
t.Fatal("expected update to fail")
}
- canvas, err := dao.NewUserCanvasDAO().GetByID("canvas-1")
+ canvas, err := dao.NewUserCanvasDAO().GetByID(ctx, dao.DB, "canvas-1")
if err != nil {
t.Fatalf("failed to get canvas: %v", err)
}
@@ -1319,6 +1331,7 @@ func ptr(v int64) *int64 { return &v }
func TestResetAgentServiceClearsPerRunState(t *testing.T) {
setupAgentSessionServiceTest(t)
+ ctx := t.Context()
initialDSL := entity.JSONMap{
"graph": map[string]any{
"nodes": []any{map[string]any{"id": "begin"}},
@@ -1354,11 +1367,11 @@ func TestResetAgentServiceClearsPerRunState(t *testing.T) {
Release: true, // pre-reset draft has a published version
DSL: initialDSL,
}
- if err := dao.DB.Create(row).Error; err != nil {
+ if err := dao.DB.WithContext(ctx).Create(row).Error; err != nil {
t.Fatalf("failed to seed canvas: %v", err)
}
- got, err := NewAgentService().ResetAgent(context.Background(), "user-1", "canvas-1")
+ got, err := NewAgentService().ResetAgent(ctx, "user-1", "canvas-1")
if err != nil {
t.Fatalf("ResetAgent failed: %v", err)
}
@@ -1402,7 +1415,7 @@ func TestResetAgentServiceClearsPerRunState(t *testing.T) {
}
// DB row was updated in place; release flipped back to false.
- persisted, err := dao.NewUserCanvasDAO().GetByID("canvas-1")
+ persisted, err := dao.NewUserCanvasDAO().GetByID(ctx, dao.DB, "canvas-1")
if err != nil {
t.Fatalf("failed to reload canvas: %v", err)
}
@@ -1423,7 +1436,8 @@ func TestResetAgentServiceClearsPerRunState(t *testing.T) {
func TestResetAgentServiceNotFound(t *testing.T) {
setupAgentSessionServiceTest(t)
- _, err := NewAgentService().ResetAgent(context.Background(), "user-1", "missing")
+ ctx := t.Context()
+ _, err := NewAgentService().ResetAgent(ctx, "user-1", "missing")
if err == nil {
t.Fatal("expected error for missing canvas")
}
@@ -1446,7 +1460,8 @@ func TestUpdateAgentSettingsPreservesDSL(t *testing.T) {
},
},
}
- if err := dao.DB.Create(&entity.UserCanvas{
+ ctx := t.Context()
+ if err := dao.DB.WithContext(ctx).Create(&entity.UserCanvas{
ID: "canvas-settings",
UserID: "user-1",
Title: sptr("Settings Agent"),
@@ -1457,14 +1472,14 @@ func TestUpdateAgentSettingsPreservesDSL(t *testing.T) {
t.Fatalf("failed to seed canvas: %v", err)
}
- err := NewAgentService().UpdateAgent(context.Background(), "user-1", "canvas-settings", map[string]interface{}{
+ err := NewAgentService().UpdateAgent(ctx, "user-1", "canvas-settings", map[string]interface{}{
"description": "new description",
})
if err != nil {
t.Fatalf("UpdateAgent failed: %v", err)
}
- persisted, err := dao.NewUserCanvasDAO().GetByID("canvas-settings")
+ persisted, err := dao.NewUserCanvasDAO().GetByID(ctx, dao.DB, "canvas-settings")
if err != nil {
t.Fatalf("failed to reload canvas: %v", err)
}
@@ -1481,8 +1496,9 @@ func TestUpdateAgentSettingsPreservesDSL(t *testing.T) {
func TestUpdateAgentAllowsExistingTitleForSameCanvas(t *testing.T) {
setupAgentSessionServiceTest(t)
+ ctx := t.Context()
- if err := dao.DB.Create(&entity.UserCanvas{
+ if err := dao.DB.WithContext(ctx).Create(&entity.UserCanvas{
ID: "canvas-same-title",
UserID: "user-1",
Title: sptr("Same Title"),
@@ -1493,7 +1509,7 @@ func TestUpdateAgentAllowsExistingTitleForSameCanvas(t *testing.T) {
t.Fatalf("failed to seed canvas: %v", err)
}
- err := NewAgentService().UpdateAgent(context.Background(), "user-1", "canvas-same-title", map[string]interface{}{
+ err := NewAgentService().UpdateAgent(ctx, "user-1", "canvas-same-title", map[string]interface{}{
"title": "Same Title",
"description": "new description",
})
@@ -1504,8 +1520,9 @@ func TestUpdateAgentAllowsExistingTitleForSameCanvas(t *testing.T) {
func TestUpdateAgentRejectsDuplicateTitleInDestinationCategory(t *testing.T) {
setupAgentSessionServiceTest(t)
+ ctx := t.Context()
- if err := dao.DB.Create(&entity.UserCanvas{
+ if err := dao.DB.WithContext(ctx).Create(&entity.UserCanvas{
ID: "canvas-source-category",
UserID: "user-1",
Title: sptr("Source Title"),
@@ -1514,7 +1531,7 @@ func TestUpdateAgentRejectsDuplicateTitleInDestinationCategory(t *testing.T) {
}).Error; err != nil {
t.Fatalf("failed to seed source canvas: %v", err)
}
- if err := dao.DB.Create(&entity.UserCanvas{
+ if err := dao.DB.WithContext(ctx).Create(&entity.UserCanvas{
ID: "canvas-destination-duplicate",
UserID: "user-1",
Title: sptr("Duplicate Title"),
@@ -1524,7 +1541,7 @@ func TestUpdateAgentRejectsDuplicateTitleInDestinationCategory(t *testing.T) {
t.Fatalf("failed to seed duplicate canvas: %v", err)
}
- err := NewAgentService().UpdateAgent(context.Background(), "user-1", "canvas-source-category", map[string]interface{}{
+ err := NewAgentService().UpdateAgent(ctx, "user-1", "canvas-source-category", map[string]interface{}{
"title": "Duplicate Title",
"canvas_category": "dataflow_canvas",
})
@@ -1555,7 +1572,8 @@ func TestUpdateAgentRejectsCategoryOnlyDuplicateTitleInDestinationCategory(t *te
t.Fatalf("failed to seed duplicate canvas: %v", err)
}
- err := NewAgentService().UpdateAgent(context.Background(), "user-1", "canvas-category-only-source", map[string]interface{}{
+ ctx := t.Context()
+ err := NewAgentService().UpdateAgent(ctx, "user-1", "canvas-category-only-source", map[string]interface{}{
"canvas_category": "dataflow_canvas",
})
if err == nil || err.Error() != "Shared Title already exists." {
@@ -1566,7 +1584,8 @@ func TestUpdateAgentRejectsCategoryOnlyDuplicateTitleInDestinationCategory(t *te
func TestUpdateAgentPersistsDSLAsJSONMap(t *testing.T) {
setupAgentSessionServiceTest(t)
- if err := dao.DB.Create(&entity.UserCanvas{
+ ctx := t.Context()
+ if err := dao.DB.WithContext(ctx).Create(&entity.UserCanvas{
ID: "canvas-dsl-update",
UserID: "user-1",
Title: sptr("DSL Agent"),
@@ -1576,7 +1595,7 @@ func TestUpdateAgentPersistsDSLAsJSONMap(t *testing.T) {
t.Fatalf("failed to seed canvas: %v", err)
}
- err := NewAgentService().UpdateAgent(context.Background(), "user-1", "canvas-dsl-update", map[string]interface{}{
+ err := NewAgentService().UpdateAgent(ctx, "user-1", "canvas-dsl-update", map[string]interface{}{
"dsl": map[string]interface{}{
"graph": map[string]interface{}{
"nodes": []interface{}{map[string]interface{}{"id": "begin"}},
@@ -1593,7 +1612,7 @@ func TestUpdateAgentPersistsDSLAsJSONMap(t *testing.T) {
t.Fatalf("UpdateAgent failed: %v", err)
}
- persisted, err := dao.NewUserCanvasDAO().GetByID("canvas-dsl-update")
+ persisted, err := dao.NewUserCanvasDAO().GetByID(ctx, dao.DB, "canvas-dsl-update")
if err != nil {
t.Fatalf("failed to reload canvas: %v", err)
}
@@ -1605,10 +1624,11 @@ func TestUpdateAgentPersistsDSLAsJSONMap(t *testing.T) {
func TestUpdateAgentDSLCreatesAndReplacesDraftVersion(t *testing.T) {
setupAgentSessionServiceTest(t)
- if err := dao.DB.Create(&entity.User{ID: "user-1", Nickname: "owner", Email: "[email protected]"}).Error; err != nil {
+ ctx := t.Context()
+ if err := dao.DB.WithContext(ctx).Create(&entity.User{ID: "user-1", Nickname: "owner", Email: "[email protected]"}).Error; err != nil {
t.Fatalf("failed to seed user: %v", err)
}
- if err := dao.DB.Create(&entity.UserCanvas{
+ if err := dao.DB.WithContext(ctx).Create(&entity.UserCanvas{
ID: "canvas-version-draft",
UserID: "user-1",
Title: sptr("Draft Agent"),
@@ -1632,18 +1652,18 @@ func TestUpdateAgentDSLCreatesAndReplacesDraftVersion(t *testing.T) {
},
},
}
- if err := NewAgentService().UpdateAgent(context.Background(), "user-1", "canvas-version-draft", patch); err != nil {
+ if err := NewAgentService().UpdateAgent(ctx, "user-1", "canvas-version-draft", patch); err != nil {
t.Fatalf("first UpdateAgent failed: %v", err)
}
secondPatch := map[string]interface{}{
"title": "Renamed Agent",
"dsl": patch["dsl"],
}
- if err := NewAgentService().UpdateAgent(context.Background(), "user-1", "canvas-version-draft", secondPatch); err != nil {
+ if err := NewAgentService().UpdateAgent(ctx, "user-1", "canvas-version-draft", secondPatch); err != nil {
t.Fatalf("second UpdateAgent failed: %v", err)
}
- versions, err := dao.NewUserCanvasVersionDAO().ListByCanvasID("canvas-version-draft")
+ versions, err := dao.NewUserCanvasVersionDAO().ListByCanvasID(ctx, dao.DB, "canvas-version-draft")
if err != nil {
t.Fatalf("failed to list versions: %v", err)
}
@@ -1654,7 +1674,7 @@ func TestUpdateAgentDSLCreatesAndReplacesDraftVersion(t *testing.T) {
t.Fatalf("unexpected version title: %v", versions[0].Title)
}
var release bool
- if err := dao.DB.Table("user_canvas_version").Select("release").Where("id = ?", versions[0].ID).Scan(&release).Error; err != nil {
+ if err = dao.DB.WithContext(ctx).Table("user_canvas_version").Select("release").Where("id = ?", versions[0].ID).Scan(&release).Error; err != nil {
t.Fatalf("failed to read release flag: %v", err)
}
if release {
@@ -1665,13 +1685,14 @@ func TestUpdateAgentDSLCreatesAndReplacesDraftVersion(t *testing.T) {
func TestPublishAgentUpdatesCanvasAndReleasedVersion(t *testing.T) {
setupAgentSessionServiceTest(t)
- if err := dao.DB.Create(&entity.User{ID: "user-1", Nickname: "owner", Email: "[email protected]"}).Error; err != nil {
+ ctx := t.Context()
+ if err := dao.DB.WithContext(ctx).Create(&entity.User{ID: "user-1", Nickname: "owner", Email: "[email protected]"}).Error; err != nil {
t.Fatalf("failed to seed user: %v", err)
}
initialDSL := entity.JSONMap{
"components": map[string]any{},
}
- if err := dao.DB.Create(&entity.UserCanvas{
+ if err := dao.DB.WithContext(ctx).Create(&entity.UserCanvas{
ID: "canvas-publish",
UserID: "user-1",
Title: sptr("Draft Agent"),
@@ -1694,7 +1715,7 @@ func TestPublishAgentUpdatesCanvasAndReleasedVersion(t *testing.T) {
},
},
}
- row, err := NewAgentService().PublishAgent(context.Background(), "user-1", "canvas-publish", &PublishAgentRequest{
+ row, err := NewAgentService().PublishAgent(ctx, "user-1", "canvas-publish", &PublishAgentRequest{
Title: &publishTitle,
Description: &description,
DSL: publishDSL,
@@ -1715,7 +1736,7 @@ func TestPublishAgentUpdatesCanvasAndReleasedVersion(t *testing.T) {
t.Fatalf("unexpected published version title: %v", row.Title)
}
- persisted, err := dao.NewUserCanvasDAO().GetByID("canvas-publish")
+ persisted, err := dao.NewUserCanvasDAO().GetByID(ctx, dao.DB, "canvas-publish")
if err != nil {
t.Fatalf("failed to reload canvas: %v", err)
}
@@ -1732,7 +1753,7 @@ func TestPublishAgentUpdatesCanvasAndReleasedVersion(t *testing.T) {
t.Fatalf("published canvas DSL was not persisted: %#v", persisted.DSL)
}
- versions, err := dao.NewUserCanvasVersionDAO().ListByCanvasID("canvas-publish")
+ versions, err := dao.NewUserCanvasVersionDAO().ListByCanvasID(ctx, dao.DB, "canvas-publish")
if err != nil {
t.Fatalf("failed to list versions: %v", err)
}
@@ -1750,7 +1771,8 @@ func TestPublishAgentUpdatesCanvasAndReleasedVersion(t *testing.T) {
func TestUpdateAgentDSLDoesNotOverwriteLatestReleasedVersion(t *testing.T) {
setupAgentSessionServiceTest(t)
- if err := dao.DB.Create(&entity.User{ID: "user-1", Nickname: "owner", Email: "[email protected]"}).Error; err != nil {
+ ctx := t.Context()
+ if err := dao.DB.WithContext(ctx).Create(&entity.User{ID: "user-1", Nickname: "owner", Email: "[email protected]"}).Error; err != nil {
t.Fatalf("failed to seed user: %v", err)
}
dsl := entity.JSONMap{
@@ -1764,7 +1786,7 @@ func TestUpdateAgentDSLDoesNotOverwriteLatestReleasedVersion(t *testing.T) {
},
},
}
- if err := dao.DB.Create(&entity.UserCanvas{
+ if err := dao.DB.WithContext(ctx).Create(&entity.UserCanvas{
ID: "canvas-released-latest",
UserID: "user-1",
Title: sptr("Released Agent"),
@@ -1774,7 +1796,7 @@ func TestUpdateAgentDSLDoesNotOverwriteLatestReleasedVersion(t *testing.T) {
t.Fatalf("failed to seed canvas: %v", err)
}
releasedAt := time.Now().Add(-time.Minute)
- if err := dao.DB.Create(&entity.UserCanvasVersion{
+ if err := dao.DB.WithContext(ctx).Create(&entity.UserCanvasVersion{
ID: "released-version",
UserCanvasID: "canvas-released-latest",
Title: sptr("released"),
@@ -1788,11 +1810,11 @@ func TestUpdateAgentDSLDoesNotOverwriteLatestReleasedVersion(t *testing.T) {
t.Fatalf("failed to seed released version: %v", err)
}
- if err := NewAgentService().UpdateAgent(context.Background(), "user-1", "canvas-released-latest", map[string]interface{}{"dsl": map[string]interface{}(dsl)}); err != nil {
+ if err := NewAgentService().UpdateAgent(ctx, "user-1", "canvas-released-latest", map[string]interface{}{"dsl": map[string]interface{}(dsl)}); err != nil {
t.Fatalf("UpdateAgent failed: %v", err)
}
- versions, err := dao.NewUserCanvasVersionDAO().ListByCanvasID("canvas-released-latest")
+ versions, err := dao.NewUserCanvasVersionDAO().ListByCanvasID(ctx, dao.DB, "canvas-released-latest")
if err != nil {
t.Fatalf("failed to list versions: %v", err)
}
@@ -1800,14 +1822,14 @@ func TestUpdateAgentDSLDoesNotOverwriteLatestReleasedVersion(t *testing.T) {
t.Fatalf("expected draft save to create a new version beside the released one, got %d", len(versions))
}
var releasedCount int64
- if err := dao.DB.Table("user_canvas_version").Where("user_canvas_id = ? AND release = ?", "canvas-released-latest", true).Count(&releasedCount).Error; err != nil {
+ if err = dao.DB.WithContext(ctx).Table("user_canvas_version").Where("user_canvas_id = ? AND release = ?", "canvas-released-latest", true).Count(&releasedCount).Error; err != nil {
t.Fatalf("failed to count released versions: %v", err)
}
if releasedCount != 1 {
t.Fatalf("released version count = %d, want 1", releasedCount)
}
var draftCount int64
- if err := dao.DB.Table("user_canvas_version").Where("user_canvas_id = ? AND release = ?", "canvas-released-latest", false).Count(&draftCount).Error; err != nil {
+ if err = dao.DB.WithContext(ctx).Table("user_canvas_version").Where("user_canvas_id = ? AND release = ?", "canvas-released-latest", false).Count(&draftCount).Error; err != nil {
t.Fatalf("failed to count draft versions: %v", err)
}
if draftCount != 1 {
@@ -1825,7 +1847,8 @@ func TestResetAgentServiceOtherTenant(t *testing.T) {
setupAgentSessionServiceTest(t)
createAgentSessionTestCanvas(t, "canvas-1", "user-2")
- _, err := NewAgentService().ResetAgent(context.Background(), "user-1", "canvas-1")
+ ctx := t.Context()
+ _, err := NewAgentService().ResetAgent(ctx, "user-1", "canvas-1")
if !errors.Is(err, dao.ErrUserCanvasNotFound) {
t.Errorf("expected ErrUserCanvasNotFound for cross-tenant access, got %v", err)
}
diff --git a/internal/service/bot.go b/internal/service/bot.go
index d26a267e30..13b96a6952 100644
--- a/internal/service/bot.go
+++ b/internal/service/bot.go
@@ -238,11 +238,11 @@ func (s *BotService) loadCanvas(ctx context.Context, tenantID, agentID string) (
return nil, dao.ErrUserCanvasNotFound
}
userTenantDAO := dao.NewUserTenantDAO()
- tenants, err := userTenantDAO.GetTenantIDsByUserID(tenantID)
+ tenants, err := userTenantDAO.GetTenantIDsByUserID(ctx, dao.DB, tenantID)
if err != nil {
return nil, fmt.Errorf("bot: tenants for user %s: %w", tenantID, err)
}
- return s.canvasDAO.GetByIDForUser(agentID, tenantID, tenants)
+ return s.canvasDAO.GetByIDForUser(ctx, dao.DB, agentID, tenantID, tenants)
}
// canvasDSLMap projects a UserCanvas.DSL JSONMap into a
diff --git a/internal/service/chat.go b/internal/service/chat.go
index 6a2b03351e..b253b020b1 100644
--- a/internal/service/chat.go
+++ b/internal/service/chat.go
@@ -101,7 +101,7 @@ func (s *ChatService) ListChats(ctx context.Context, userID, status, keywords st
}
} else {
var filterOwnerIDs []string
- filterOwnerIDs, err = s.filterAccessibleChatOwnerIDs(userID, ownerIDs)
+ filterOwnerIDs, err = s.filterAccessibleChatOwnerIDs(ctx, userID, ownerIDs)
if err != nil {
return nil, err
}
@@ -150,8 +150,8 @@ func (s *ChatService) ListChats(ctx context.Context, userID, status, keywords st
}, nil
}
-func (s *ChatService) filterAccessibleChatOwnerIDs(userID string, ownerIDs []string) ([]string, error) {
- tenantIDs, err := s.userTenantDAO.GetTenantIDsByUserID(userID)
+func (s *ChatService) filterAccessibleChatOwnerIDs(ctx context.Context, userID string, ownerIDs []string) ([]string, error) {
+ tenantIDs, err := s.userTenantDAO.GetTenantIDsByUserID(ctx, dao.DB, userID)
if err != nil {
return nil, err
}
@@ -1267,7 +1267,7 @@ type GetChatResponse struct {
// GetChat gets chat detail by ID with permission check
func (s *ChatService) GetChat(ctx context.Context, userID string, chatID string) (*GetChatResponse, error) {
// Step 1: Get user tenants (same as Python UserTenantService.query(user_id=current_user.id))
- tenants, err := s.userTenantDAO.GetByUserID(userID)
+ tenants, err := s.userTenantDAO.GetByUserID(ctx, dao.DB, userID)
if err != nil {
return nil, fmt.Errorf("failed to get user tenants: %w", err)
}
diff --git a/internal/service/chat_channel.go b/internal/service/chat_channel.go
index 63c4af526e..b672f3f29a 100644
--- a/internal/service/chat_channel.go
+++ b/internal/service/chat_channel.go
@@ -110,7 +110,7 @@ func (s *ChatChannelService) accessible(ctx context.Context, userID, channelID s
return channel, true, nil
}
- tenantIDs, err := s.userTenantDAO.GetTenantIDsByUserID(userID)
+ tenantIDs, err := s.userTenantDAO.GetTenantIDsByUserID(ctx, dao.DB, userID)
if err != nil {
return nil, false, err
}
diff --git a/internal/service/chat_session.go b/internal/service/chat_session.go
index dd3ae48a24..fe1f8c8c6d 100644
--- a/internal/service/chat_session.go
+++ b/internal/service/chat_session.go
@@ -52,7 +52,7 @@ type chatSessionStore interface {
}
type userTenantStore interface {
- GetTenantIDsByUserID(userID string) ([]string, error)
+ GetTenantIDsByUserID(ctx context.Context, db *gorm.DB, userID string) ([]string, error)
}
type chatPipelineRunner interface {
@@ -177,7 +177,7 @@ func (s *ChatSessionService) SetChatSession(ctx context.Context, userID string,
// RemoveChatSessions removes chat sessions.
// Kept as a compatibility entrypoint for older chat-session callers.
func (s *ChatSessionService) RemoveChatSessions(ctx context.Context, userID string, chatSessions []string) error {
- tenantIDs, err := s.userTenantDAO.GetTenantIDsByUserID(userID)
+ tenantIDs, err := s.userTenantDAO.GetTenantIDsByUserID(ctx, dao.DB, userID)
if err != nil {
return err
}
@@ -191,7 +191,7 @@ func (s *ChatSessionService) RemoveChatSessions(ctx context.Context, userID stri
for _, convID := range chatSessions {
session, err := s.chatSessionDAO.GetByID(ctx, dao.DB, convID)
if err != nil {
- return fmt.Errorf("Chat session not found: %s", convID)
+ return fmt.Errorf("chat session not found: %s", convID)
}
isOwner := false
@@ -206,7 +206,7 @@ func (s *ChatSessionService) RemoveChatSessions(ctx context.Context, userID stri
}
}
if !isOwner {
- return errors.New("Only owner of chat session authorized for this operation")
+ return errors.New("only owner of chat session authorized for this operation")
}
if err = s.chatSessionDAO.DeleteByID(ctx, dao.DB, convID); err != nil {
@@ -244,7 +244,7 @@ type ChatSessionPayload struct {
// ListChatSessions lists chat sessions for a dialog
func (s *ChatSessionService) ListChatSessions(ctx context.Context, userID string, chatID string) (*ListChatSessionsResponse, error) {
// Get user's tenants
- tenantIDs, err := s.userTenantDAO.GetTenantIDsByUserID(userID)
+ tenantIDs, err := s.userTenantDAO.GetTenantIDsByUserID(ctx, dao.DB, userID)
if err != nil {
return nil, err
}
@@ -293,18 +293,18 @@ func (s *ChatSessionService) GetSession(ctx context.Context, userID, chatID, ses
return nil, common.CodeServerError, err
}
if !ok {
- return nil, common.CodeAuthenticationError, errors.New("No authorization.")
+ return nil, common.CodeAuthenticationError, errors.New("no authorization")
}
session, err := s.chatSessionDAO.GetByID(ctx, dao.DB, sessionID)
if err != nil {
if isChatSessionNotFound(err) {
- return nil, common.CodeDataError, errors.New("Session not found!")
+ return nil, common.CodeDataError, errors.New("session not found")
}
return nil, common.CodeServerError, err
}
if session.DialogID != chatID {
- return nil, common.CodeDataError, errors.New("Session does not belong to this chat!")
+ return nil, common.CodeDataError, errors.New("session does not belong to this chat")
}
dialog, err := s.chatSessionDAO.GetDialogByID(ctx, dao.DB, chatID)
@@ -322,13 +322,13 @@ func (s *ChatSessionService) CreateSession(ctx context.Context, userID, chatID s
return nil, common.CodeServerError, err
}
if !ok {
- return nil, common.CodeAuthenticationError, errors.New("No authorization.")
+ return nil, common.CodeAuthenticationError, errors.New("no authorization")
}
dialog, err := s.chatSessionDAO.GetDialogByID(ctx, dao.DB, chatID)
if err != nil {
if isChatSessionNotFound(err) {
- return nil, common.CodeDataError, errors.New("Chat not found!")
+ return nil, common.CodeDataError, errors.New("chat not found")
}
return nil, common.CodeServerError, err
}
@@ -337,7 +337,7 @@ func (s *ChatSessionService) CreateSession(ctx context.Context, userID, chatID s
if rawName, exists := req["name"]; exists {
nameStr, ok := rawName.(string)
if !ok || strings.TrimSpace(nameStr) == "" {
- return nil, common.CodeDataError, errors.New("`name` can not be empty.")
+ return nil, common.CodeDataError, errors.New("`name` can not be empty")
}
name = strings.TrimSpace(nameStr)
}
@@ -371,12 +371,12 @@ func (s *ChatSessionService) CreateSession(ctx context.Context, userID, chatID s
}
if err = s.chatSessionDAO.Create(ctx, dao.DB, conv); err != nil {
- return nil, common.CodeDataError, errors.New("Fail to create a session!")
+ return nil, common.CodeDataError, errors.New("fail to create a session")
}
session, err := s.chatSessionDAO.GetByID(ctx, dao.DB, conv.ID)
if err != nil {
- return nil, common.CodeDataError, errors.New("Fail to create a session!")
+ return nil, common.CodeDataError, errors.New("fail to create a session")
}
return s.buildSessionPayload(session, nil, false), common.CodeSuccess, nil
}
@@ -388,7 +388,7 @@ func (s *ChatSessionService) DeleteSessions(ctx context.Context, userID, chatID
return nil, "", common.CodeServerError, err
}
if !ok {
- return false, "No authorization.", common.CodeAuthenticationError, errors.New("No authorization.")
+ return false, "no authorization", common.CodeAuthenticationError, errors.New("no authorization")
}
if len(req) == 0 {
@@ -546,33 +546,33 @@ func (s *ChatSessionService) UpdateSession(ctx context.Context, userID, chatID,
return nil, common.CodeServerError, err
}
if !ok {
- return nil, common.CodeAuthenticationError, errors.New("No authorization.")
+ return nil, common.CodeAuthenticationError, errors.New("no authorization")
}
if len(req) == 0 {
- return nil, common.CodeArgumentError, errors.New("Request body cannot be empty")
+ return nil, common.CodeArgumentError, errors.New("request body cannot be empty")
}
- if _, err := s.chatSessionDAO.GetBySessionIDAndChatID(ctx, dao.DB, sessionID, chatID); err != nil {
+ if _, err = s.chatSessionDAO.GetBySessionIDAndChatID(ctx, dao.DB, sessionID, chatID); err != nil {
if isChatSessionNotFound(err) {
- return nil, common.CodeDataError, errors.New("Session not found!")
+ return nil, common.CodeDataError, errors.New("session not found")
}
return nil, common.CodeServerError, err
}
- if _, ok := req["message"]; ok {
- return nil, common.CodeDataError, errors.New("`messages` cannot be changed.")
+ if _, ok = req["message"]; ok {
+ return nil, common.CodeDataError, errors.New("`messages` cannot be changed")
}
- if _, ok := req["messages"]; ok {
- return nil, common.CodeDataError, errors.New("`messages` cannot be changed.")
+ if _, ok = req["messages"]; ok {
+ return nil, common.CodeDataError, errors.New("`messages` cannot be changed")
}
- if _, ok := req["reference"]; ok {
- return nil, common.CodeDataError, errors.New("`reference` cannot be changed.")
+ if _, ok = req["reference"]; ok {
+ return nil, common.CodeDataError, errors.New("`reference` cannot be changed")
}
if name, exists := req["name"]; exists && name != nil {
nameStr, ok := name.(string)
if !ok || strings.TrimSpace(nameStr) == "" {
- return nil, common.CodeDataError, errors.New("`name` can not be empty.")
+ return nil, common.CodeDataError, errors.New("`name` can not be empty")
}
req["name"] = strings.TrimSpace(nameStr)
nameRunes := []rune(req["name"].(string))
@@ -593,7 +593,7 @@ func (s *ChatSessionService) UpdateSession(ctx context.Context, userID, chatID,
if err = s.chatSessionDAO.UpdateByID(ctx, dao.DB, sessionID, updateFields); err != nil {
if isChatSessionNotFound(err) {
- return nil, common.CodeDataError, errors.New("Session not found!")
+ return nil, common.CodeDataError, errors.New("session not found")
}
return nil, common.CodeServerError, err
}
@@ -601,7 +601,7 @@ func (s *ChatSessionService) UpdateSession(ctx context.Context, userID, chatID,
session, err := s.chatSessionDAO.GetByID(ctx, dao.DB, sessionID)
if err != nil {
if isChatSessionNotFound(err) {
- return nil, common.CodeDataError, errors.New("Fail to update a session!")
+ return nil, common.CodeDataError, errors.New("fail to update a session")
}
return nil, common.CodeServerError, err
}
@@ -615,7 +615,7 @@ func (s *ChatSessionService) DeleteSessionMessage(ctx context.Context, userID, c
return nil, common.CodeServerError, err
}
if !ok {
- return nil, common.CodeAuthenticationError, errors.New("No authorization.")
+ return nil, common.CodeAuthenticationError, errors.New("no authorization")
}
session, err := s.chatSessionDAO.GetByID(ctx, dao.DB, sessionID)
@@ -623,7 +623,7 @@ func (s *ChatSessionService) DeleteSessionMessage(ctx context.Context, userID, c
if err != nil && !isChatSessionNotFound(err) {
return nil, common.CodeServerError, err
}
- return nil, common.CodeDataError, errors.New("Session not found!")
+ return nil, common.CodeDataError, errors.New("session not found")
}
// parseMessages / parseReferenceList return nil for
@@ -631,11 +631,11 @@ func (s *ChatSessionService) DeleteSessionMessage(ctx context.Context, userID, c
// the single source of truth for "this blob is corrupt".
messages := parseMessages(session.Message)
if len(session.Message) > 0 && messages == nil {
- return nil, common.CodeDataError, errors.New("Invalid session messages")
+ return nil, common.CodeDataError, errors.New("invalid session messages")
}
references := parseReferenceList(session.Reference)
if len(session.Reference) > 0 && references == nil {
- return nil, common.CodeDataError, errors.New("Invalid session reference")
+ return nil, common.CodeDataError, errors.New("invalid session reference")
}
for i, msg := range messages {
if msgID != stringValue(msg["id"]) {
@@ -680,7 +680,7 @@ func (s *ChatSessionService) UpdateMessageFeedback(ctx context.Context, userID,
ctx = context.Background()
}
ownerTenantID := ""
- tenantIDs, err := s.userTenantDAO.GetTenantIDsByUserID(userID)
+ tenantIDs, err := s.userTenantDAO.GetTenantIDsByUserID(ctx, dao.DB, userID)
if err != nil {
return nil, common.CodeServerError, err
}
@@ -705,7 +705,7 @@ func (s *ChatSessionService) UpdateMessageFeedback(ctx context.Context, userID,
}
ok := ownerTenantID != ""
if !ok {
- return nil, common.CodeAuthenticationError, errors.New("No authorization.")
+ return nil, common.CodeAuthenticationError, errors.New("no authorization")
}
session, err := s.chatSessionDAO.GetByID(ctx, dao.DB, sessionID)
@@ -713,28 +713,28 @@ func (s *ChatSessionService) UpdateMessageFeedback(ctx context.Context, userID,
if err != nil && !isChatSessionNotFound(err) {
return nil, common.CodeServerError, err
}
- return nil, common.CodeDataError, errors.New("Session not found!")
+ return nil, common.CodeDataError, errors.New("session not found")
}
thumbRaw, ok := req["thumbup"]
if !ok {
- return nil, common.CodeDataError, errors.New("thumbup must be a boolean")
+ return nil, common.CodeDataError, errors.New("thumb-up must be a boolean")
}
thumbup, ok := thumbRaw.(bool)
if !ok {
- return nil, common.CodeDataError, errors.New("thumbup must be a boolean")
+ return nil, common.CodeDataError, errors.New("thumb-up must be a boolean")
}
messages := parseMessages(session.Message)
if len(session.Message) > 0 && messages == nil {
- return nil, common.CodeDataError, errors.New("Invalid session messages")
+ return nil, common.CodeDataError, errors.New("invalid session messages")
}
// References are only used later in this function but a
// malformed blob must surface immediately, not silently
// collapse to an empty slice.
references := parseReferenceList(session.Reference)
if len(session.Reference) > 0 && references == nil {
- return nil, common.CodeDataError, errors.New("Invalid session reference")
+ return nil, common.CodeDataError, errors.New("invalid session reference")
}
messageIndex := -1
var priorThumb interface{}
@@ -763,10 +763,6 @@ func (s *ChatSessionService) UpdateMessageFeedback(ctx context.Context, userID,
}
if messageIndex != -1 && applyChunkFeedback {
- references := parseReferenceList(session.Reference)
- if len(session.Reference) > 0 && references == nil {
- return nil, common.CodeDataError, errors.New("Invalid session reference")
- }
refIndex := (messageIndex - 1) / 2
if refIndex >= 0 && refIndex < len(references) {
if reference, ok := references[refIndex].(map[string]interface{}); ok && len(reference) > 0 {
@@ -1037,7 +1033,7 @@ func (s *ChatSessionService) updateChunkWeight(ctx context.Context, tenantID, ch
indexName := fmt.Sprintf("ragflow_%s", tenantID)
if adjuster, ok := docEngine.(chunkPagerankAdjuster); ok {
if err := adjuster.AdjustChunkPagerank(ctx, indexName, chunkID, kbID, delta, minPagerankWeight, maxPagerankWeight); err != nil {
- common.Warn("Failed atomic pagerank adjust for chunk",
+ common.Warn("Failed atomic PageRank adjust for chunk",
zap.String("chunk_id", chunkID),
zap.Error(err),
)
@@ -1080,7 +1076,7 @@ func (s *ChatSessionService) updateChunkWeight(ctx context.Context, tenantID, ch
newValue = map[string]interface{}{"remove": common.PAGERANK_FLD}
}
if err := docEngine.UpdateChunks(ctx, map[string]interface{}{"id": chunkID}, newValue, indexName, kbID); err != nil {
- common.Warn("Failed to update chunk pagerank",
+ common.Warn("Failed to update chunk PageRank",
zap.String("chunk_id", chunkID),
zap.Error(err),
)
@@ -1113,7 +1109,7 @@ func floatValue(value interface{}) (float64, bool) {
}
func (s *ChatSessionService) ensureOwnedChat(ctx context.Context, userID, chatID string) (bool, error) {
- tenantIDs, err := s.userTenantDAO.GetTenantIDsByUserID(userID)
+ tenantIDs, err := s.userTenantDAO.GetTenantIDsByUserID(ctx, dao.DB, userID)
if err != nil {
return false, err
}
@@ -1276,12 +1272,12 @@ func (s *ChatSessionService) Completion(ctx context.Context, userID string, conv
session, err := s.chatSessionDAO.GetByID(ctx, dao.DB, conversationID)
if err != nil {
- return nil, errors.New("Conversation not found")
+ return nil, errors.New("conversation not found")
}
dialog, err := s.chatSessionDAO.GetDialogByID(ctx, dao.DB, session.DialogID)
if err != nil {
- return nil, errors.New("Dialog not found")
+ return nil, errors.New("dialog not found")
}
sessionMessages := s.buildSessionMessages(session, messages)
@@ -1291,7 +1287,7 @@ func (s *ChatSessionService) Completion(ctx context.Context, userID string, conv
if llmID != "" {
hasKey, err := s.checkTenantLLMAPIKey(ctx, dialog.TenantID, llmID)
if err != nil || !hasKey {
- return nil, fmt.Errorf("Cannot use specified model %s", llmID)
+ return nil, fmt.Errorf("cannot use specified model %s", llmID)
}
dialog.LLMID = llmID
if chatModelConfig != nil {
@@ -1347,10 +1343,6 @@ func (s *ChatSessionService) Completion(ctx context.Context, userID string, conv
// CompletionStream performs streaming chat completion with full RAG support via ChatPipelineService.
// Kept as a compatibility entrypoint for callers that still use the pre-ChatCompletions API.
func (s *ChatSessionService) CompletionStream(ctx context.Context, userID string, conversationID string, messages []map[string]interface{}, llmID string, chatModelConfig map[string]interface{}, messageID string, streamChan chan<- string) error {
- if ctx == nil {
- ctx = context.Background()
- }
-
if len(messages) == 0 {
streamChan <- fmt.Sprintf("data: %s\n\n", `{"code": 500, "message": "messages cannot be empty", "data": {"answer": "**ERROR**: messages cannot be empty", "reference": []}}`)
return errors.New("messages cannot be empty")
@@ -1382,7 +1374,7 @@ func (s *ChatSessionService) CompletionStream(ctx context.Context, userID string
if err != nil || !hasKey {
errMsg := fmt.Sprintf(`{"code": 500, "message": "Cannot use specified model %s", "data": {"answer": "**ERROR**: Cannot use specified model", "reference": []}}`, llmID)
streamChan <- fmt.Sprintf("data: %s\n\n", errMsg)
- return fmt.Errorf("Cannot use specified model %s", llmID)
+ return fmt.Errorf("cannot use specified model %s", llmID)
}
dialog.LLMID = llmID
if chatModelConfig != nil {
@@ -1484,7 +1476,7 @@ func (s *ChatSessionService) ChatCompletions(
// --- 2. Validate ---
if sessionID != "" && chatID == "" {
- return fail(errors.New("`chat_id` is required when `session_id` is provided."))
+ return fail(errors.New("`chat_id` is required when `session_id` is provided"))
}
// --- 3. Resolve dialog and session ---
@@ -1496,15 +1488,15 @@ func (s *ChatSessionService) ChatCompletions(
}
dialog, err = s.chatSessionDAO.GetDialogByID(ctx, dao.DB, chatID)
if err != nil {
- return fail(errors.New("Chat not found!"))
+ return fail(errors.New("chat not found"))
}
if sessionID != "" {
session, err = s.chatSessionDAO.GetByID(ctx, dao.DB, sessionID)
if err != nil {
- return fail(errors.New("Session not found!"))
+ return fail(errors.New("session not found"))
}
if session.DialogID != chatID {
- return fail(errors.New("Session does not belong to this chat!"))
+ return fail(errors.New("session does not belong to this chat"))
}
} else {
session, err = s.createSessionForCompletion(ctx, chatID, dialog, userID)
@@ -1783,7 +1775,7 @@ func (s *ChatSessionService) checkDialogOwnership(ctx context.Context, userID, c
return err
}
if !ok {
- return errors.New("No authorization.")
+ return errors.New("no authorization")
}
return nil
}
diff --git a/internal/service/chat_session_contract_test.go b/internal/service/chat_session_contract_test.go
index f1978bea15..1682f8d681 100644
--- a/internal/service/chat_session_contract_test.go
+++ b/internal/service/chat_session_contract_test.go
@@ -74,7 +74,7 @@ func TestCreateSession_RejectsEmptyOrNonStringName(t *testing.T) {
ctx := t.Context()
for _, name := range []interface{}{"", " ", 1} {
_, code, err := svc.CreateSession(ctx, "user-1", "chat-1", map[string]interface{}{"name": name})
- if err == nil || err.Error() != "`name` can not be empty." {
+ if err == nil || err.Error() != "`name` can not be empty" {
t.Fatalf("name=%#v err=%v", name, err)
}
if code != common.CodeDataError {
@@ -118,7 +118,7 @@ func TestCreateSession_NotOwner(t *testing.T) {
ctx := t.Context()
_, code, err := svc.CreateSession(ctx, "user-1", "chat-1", map[string]interface{}{"name": "x"})
- if err == nil || err.Error() != "No authorization." {
+ if err == nil || err.Error() != "no authorization" {
t.Fatalf("err=%v", err)
}
if code != common.CodeAuthenticationError {
@@ -208,7 +208,7 @@ func TestDeleteSessions_NotOwner(t *testing.T) {
ctx := t.Context()
_, _, code, err := svc.DeleteSessions(ctx, "user-1", "chat-1", map[string]interface{}{"ids": []interface{}{"s1"}})
- if err == nil || err.Error() != "No authorization." {
+ if err == nil || err.Error() != "no authorization" {
t.Fatalf("err=%v", err)
}
if code != common.CodeAuthenticationError {
diff --git a/internal/service/chat_session_test.go b/internal/service/chat_session_test.go
index 2161cb3845..d766471e6f 100644
--- a/internal/service/chat_session_test.go
+++ b/internal/service/chat_session_test.go
@@ -151,7 +151,7 @@ type fakeTenantStore struct {
err error
}
-func (f *fakeTenantStore) GetTenantIDsByUserID(userID string) ([]string, error) {
+func (f *fakeTenantStore) GetTenantIDsByUserID(ctx context.Context, db *gorm.DB, userID string) ([]string, error) {
return f.tenantIDs, f.err
}
@@ -388,7 +388,7 @@ func TestGetSession_NotOwner(t *testing.T) {
ctx := t.Context()
_, code, err := svc.GetSession(ctx, "user-1", "chat-1", "session-1")
- if err == nil || err.Error() != "No authorization." {
+ if err == nil || err.Error() != "no authorization" {
t.Fatalf("err=%v", err)
}
if code != common.CodeAuthenticationError {
@@ -409,7 +409,7 @@ func TestGetSession_WrongChat(t *testing.T) {
ctx := t.Context()
_, code, err := svc.GetSession(ctx, "user-1", "chat-1", "session-1")
- if err == nil || err.Error() != "Session does not belong to this chat!" {
+ if err == nil || err.Error() != "session does not belong to this chat" {
t.Fatalf("err=%v", err)
}
if code != common.CodeDataError {
@@ -480,11 +480,11 @@ func TestUpdateSession_ValidationErrors(t *testing.T) {
message string
code common.ErrorCode
}{
- {name: "empty body", req: map[string]interface{}{}, message: "Request body cannot be empty", code: common.CodeArgumentError},
- {name: "message", req: map[string]interface{}{"message": []interface{}{}}, message: "`messages` cannot be changed.", code: common.CodeDataError},
- {name: "messages", req: map[string]interface{}{"messages": []interface{}{}}, message: "`messages` cannot be changed.", code: common.CodeDataError},
- {name: "reference", req: map[string]interface{}{"reference": []interface{}{}}, message: "`reference` cannot be changed.", code: common.CodeDataError},
- {name: "empty name", req: map[string]interface{}{"name": " "}, message: "`name` can not be empty.", code: common.CodeDataError},
+ {name: "empty body", req: map[string]interface{}{}, message: "request body cannot be empty", code: common.CodeArgumentError},
+ {name: "message", req: map[string]interface{}{"message": []interface{}{}}, message: "`messages` cannot be changed", code: common.CodeDataError},
+ {name: "messages", req: map[string]interface{}{"messages": []interface{}{}}, message: "`messages` cannot be changed", code: common.CodeDataError},
+ {name: "reference", req: map[string]interface{}{"reference": []interface{}{}}, message: "`reference` cannot be changed", code: common.CodeDataError},
+ {name: "empty name", req: map[string]interface{}{"name": " "}, message: "`name` can not be empty", code: common.CodeDataError},
}
for _, tc := range cases {
@@ -513,7 +513,7 @@ func TestUpdateSession_NotFound(t *testing.T) {
ctx := t.Context()
_, code, err := svc.UpdateSession(ctx, "user-1", "chat-1", "missing", map[string]interface{}{"name": "renamed"})
- if err == nil || err.Error() != "Session not found!" {
+ if err == nil || err.Error() != "session not found" {
t.Fatalf("err=%v", err)
}
if code != common.CodeDataError {
@@ -1151,8 +1151,8 @@ func TestCompletion_ConversationNotFound(t *testing.T) {
_, err := svc.Completion(ctx, "user-1", "missing", []map[string]interface{}{
{"role": "user", "content": "hi"},
}, "", nil, "msg-1")
- if err == nil || err.Error() != "Conversation not found" {
- t.Fatalf("expected 'Conversation not found', got %v", err)
+ if err == nil || err.Error() != "conversation not found" {
+ t.Fatalf("expected 'conversation not found', got %v", err)
}
}
@@ -1174,8 +1174,8 @@ func TestCompletion_DialogNotFound(t *testing.T) {
_, err := svc.Completion(ctx, "user-1", "session-1", []map[string]interface{}{
{"role": "user", "content": "hi"},
}, "", nil, "msg-1")
- if err == nil || err.Error() != "Dialog not found" {
- t.Fatalf("expected 'Dialog not found', got %v", err)
+ if err == nil || err.Error() != "dialog not found" {
+ t.Fatalf("expected 'dialog not found', got %v", err)
}
}
diff --git a/internal/service/chunk/chunk.go b/internal/service/chunk/chunk.go
index 3caab50d5a..ef6f460a90 100644
--- a/internal/service/chunk/chunk.go
+++ b/internal/service/chunk/chunk.go
@@ -160,7 +160,7 @@ func (s *ChunkService) RetrievalTest(ctx context.Context, req *service.Retrieval
return nil, fmt.Errorf("dataset_ids is required")
}
- tenants, err := s.userTenantDAO.GetByUserID(userID)
+ tenants, err := s.userTenantDAO.GetByUserID(ctx, dao.DB, userID)
if err != nil {
return nil, fmt.Errorf("failed to get user tenants: %w", err)
}
@@ -512,7 +512,7 @@ func (s *ChunkService) Get(ctx context.Context, req *service.GetChunkRequest, us
}
// Get user's tenants
- tenants, err := s.userTenantDAO.GetByUserID(userID)
+ tenants, err := s.userTenantDAO.GetByUserID(ctx, dao.DB, userID)
if err != nil {
return nil, fmt.Errorf("failed to get user tenants: %w", err)
}
@@ -787,7 +787,7 @@ func (s *ChunkService) List(ctx context.Context, req *service.ListChunksRequest,
}
// Get user's tenants
- tenants, err := s.userTenantDAO.GetByUserID(userID)
+ tenants, err := s.userTenantDAO.GetByUserID(ctx, dao.DB, userID)
if err != nil {
return nil, fmt.Errorf("failed to get user tenants: %w", err)
}
@@ -1013,7 +1013,7 @@ func (s *ChunkService) SwitchChunks(ctx context.Context, userID, datasetID, docu
}
// Get user's tenants
- tenants, err := s.userTenantDAO.GetByUserID(userID)
+ tenants, err := s.userTenantDAO.GetByUserID(ctx, dao.DB, userID)
if err != nil {
return fmt.Errorf("failed to get user tenants: %w", err)
}
@@ -1070,7 +1070,7 @@ func (s *ChunkService) UpdateChunk(ctx context.Context, req *service.UpdateChunk
}
// Get user's tenants
- tenants, err := s.userTenantDAO.GetByUserID(userID)
+ tenants, err := s.userTenantDAO.GetByUserID(ctx, dao.DB, userID)
if err != nil {
return fmt.Errorf("failed to get user tenants: %w", err)
}
@@ -1209,7 +1209,7 @@ func (s *ChunkService) RemoveChunks(ctx context.Context, req *service.RemoveChun
}
// Get user's tenants
- tenants, err := s.userTenantDAO.GetByUserID(userID)
+ tenants, err := s.userTenantDAO.GetByUserID(ctx, dao.DB, userID)
if err != nil {
return 0, fmt.Errorf("failed to get user tenants: %w", err)
}
diff --git a/internal/service/chunk_types.go b/internal/service/chunk_types.go
index 69a6ac3e7f..88e6f21086 100644
--- a/internal/service/chunk_types.go
+++ b/internal/service/chunk_types.go
@@ -123,7 +123,7 @@ type ErrorCoder interface {
}
// Get retrieves a chunk by ID
-func (s *ChunkService) Get(req *GetChunkRequest, userID string) (*GetChunkResponse, error) {
+func (s *ChunkService) Get(ctx context.Context, req *GetChunkRequest, userID string) (*GetChunkResponse, error) {
if s.docEngine == nil {
return nil, fmt.Errorf("doc engine not initialized")
}
@@ -132,10 +132,8 @@ func (s *ChunkService) Get(req *GetChunkRequest, userID string) (*GetChunkRespon
return nil, fmt.Errorf("chunk_id is required")
}
- ctx := context.Background()
-
// Get user's tenants
- tenants, err := s.userTenantDAO.GetByUserID(userID)
+ tenants, err := s.userTenantDAO.GetByUserID(ctx, dao.DB, userID)
if err != nil {
return nil, fmt.Errorf("failed to get user tenants: %w", err)
}
@@ -354,7 +352,7 @@ func (s *ChunkService) List(ctx context.Context, req *ListChunksRequest, userID
}
// Get user's tenants
- tenants, err := s.userTenantDAO.GetByUserID(userID)
+ tenants, err := s.userTenantDAO.GetByUserID(ctx, dao.DB, userID)
if err != nil {
return nil, fmt.Errorf("failed to get user tenants: %w", err)
}
@@ -525,7 +523,7 @@ func (s *ChunkService) UpdateChunk(ctx context.Context, req *UpdateChunkRequest,
}
// Get user's tenants
- tenants, err := s.userTenantDAO.GetByUserID(userID)
+ tenants, err := s.userTenantDAO.GetByUserID(ctx, dao.DB, userID)
if err != nil {
return fmt.Errorf("failed to get user tenants: %w", err)
}
@@ -715,7 +713,7 @@ type RemoveChunksRequest struct {
// RemoveChunks removes chunks from the dataset table.
// If ChunkIDs is empty and DeleteAll is true, removes all chunks for the document.
-// Otherwise removes only the specified chunks.
+// Otherwise, removes only the specified chunks.
func (s *ChunkService) RemoveChunks(ctx context.Context, req *RemoveChunksRequest, userID string) (int64, error) {
if s.docEngine == nil {
return 0, fmt.Errorf("doc engine not initialized")
@@ -726,7 +724,7 @@ func (s *ChunkService) RemoveChunks(ctx context.Context, req *RemoveChunksReques
}
// Get user's tenants
- tenants, err := s.userTenantDAO.GetByUserID(userID)
+ tenants, err := s.userTenantDAO.GetByUserID(ctx, dao.DB, userID)
if err != nil {
return 0, fmt.Errorf("failed to get user tenants: %w", err)
}
diff --git a/internal/service/connector.go b/internal/service/connector.go
index 45b98fd744..6dd611d3af 100644
--- a/internal/service/connector.go
+++ b/internal/service/connector.go
@@ -74,7 +74,7 @@ var (
var (
// ErrConnectorNotFound mirrors Python's "Can't find this Connector!".
ErrConnectorNotFound = errors.New("can't find this Connector")
- // ErrConnectorNoAuth mirrors Python's "No authorization." denial.
+ // ErrConnectorNoAuth mirrors Python's "no authorization" denial.
ErrConnectorNoAuth = errors.New("no authorization")
// ErrConnectorTestUnsupported is returned for connector sources whose
// validation path is not yet ported to Go.
@@ -216,13 +216,18 @@ type boxOAuthTokenResponse struct {
}
// canAccessConnector Test Authentication
-func (s *ConnectorService) canAccessConnector(connector *entity.Connector, userID string) bool {
+func (s *ConnectorService) canAccessConnector(ctx context.Context, connector *entity.Connector, userID string) (bool, error) {
if connector.TenantID == userID {
- return true
+ return true, nil
}
-
- _, err := s.userTenantDAO.FilterByUserIDAndTenantID(userID, connector.TenantID)
- return err == nil
+ _, err := s.userTenantDAO.FilterByUserIDAndTenantID(ctx, dao.DB, userID, connector.TenantID)
+ if err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return false, nil
+ }
+ return false, err
+ }
+ return true, nil
}
// cancelConnectorTasks Stop connector tasks
@@ -289,7 +294,7 @@ func (s *ConnectorService) GetConnector(ctx context.Context, connectorID, userID
return connector, common.CodeSuccess, nil
}
- tenantIDs, err := s.userTenantDAO.GetTenantIDsByUserID(userID)
+ tenantIDs, err := s.userTenantDAO.GetTenantIDsByUserID(ctx, dao.DB, userID)
if err != nil {
return nil, common.CodeServerError, err
}
@@ -332,7 +337,7 @@ func (s *ConnectorService) accessible(ctx context.Context, connectorID, userID s
return true, nil
}
- tenantIDs, err := s.userTenantDAO.GetTenantIDsByUserID(userID)
+ tenantIDs, err := s.userTenantDAO.GetTenantIDsByUserID(ctx, dao.DB, userID)
if err != nil {
return false, err
}
@@ -841,7 +846,11 @@ func (s *ConnectorService) DeleteConnector(ctx context.Context, connectorID, use
return false, common.CodeServerError, err
}
- if !s.canAccessConnector(connector, userID) {
+ canAccess, err := s.canAccessConnector(ctx, connector, userID)
+ if err != nil {
+ return false, common.CodeServerError, err
+ }
+ if !canAccess {
return false, common.CodeAuthenticationError, fmt.Errorf("no authorization")
}
@@ -877,7 +886,11 @@ func (s *ConnectorService) UpdateConnector(ctx context.Context, connectorID, use
return nil, common.CodeServerError, err
}
- if !s.canAccessConnector(connector, userID) {
+ canAccess, err := s.canAccessConnector(ctx, connector, userID)
+ if err != nil {
+ return nil, common.CodeServerError, err
+ }
+ if !canAccess {
return nil, common.CodeAuthenticationError, fmt.Errorf("no authorization")
}
@@ -960,7 +973,11 @@ func (s *ConnectorService) RebuildConnector(ctx context.Context, connectorID, us
return false, common.CodeServerError, err
}
- if !s.canAccessConnector(connector, userID) {
+ canAccess, err := s.canAccessConnector(ctx, connector, userID)
+ if err != nil {
+ return false, common.CodeServerError, err
+ }
+ if !canAccess {
return false, common.CodeAuthenticationError, fmt.Errorf("no authorization")
}
@@ -1003,7 +1020,11 @@ func (s *ConnectorService) ListLog(ctx context.Context, connectorID, userID stri
return nil, 0, common.CodeServerError, err
}
- if !s.canAccessConnector(connector, userID) {
+ canAccess, err := s.canAccessConnector(ctx, connector, userID)
+ if err != nil {
+ return nil, 0, common.CodeServerError, err
+ }
+ if !canAccess {
return nil, 0, common.CodeAuthenticationError, fmt.Errorf("no authorization")
}
diff --git a/internal/service/dataset/create_test.go b/internal/service/dataset/create_test.go
index 947ab1ec84..06b6513ef4 100644
--- a/internal/service/dataset/create_test.go
+++ b/internal/service/dataset/create_test.go
@@ -157,7 +157,7 @@ func TestCreateDataset_ValidatesName(t *testing.T) {
if code != common.CodeDataError {
t.Fatalf("expected data error code, got %d", code)
}
- if err.Error() != "Dataset name can't be empty." {
+ if err.Error() != "dataset name can't be empty" {
t.Fatalf("unexpected error: %v", err)
}
}
@@ -197,13 +197,13 @@ func TestCreateDataset_RejectsInvalidEmbeddingModel(t *testing.T) {
embeddingModel string
expectedMessage string
}{
- {"empty", "", "Embedding model identifier must follow <model_name>@<provider> format"},
- {"whitespace", " ", "Embedding model identifier must follow <model_name>@<provider> format"},
- {"missing_at", "BAAI/bge-small-en-v1.5Builtin", "Embedding model identifier must follow <model_name>@<provider> format"},
- {"empty_model_name", "@Builtin", "Both model_name and provider must be non-empty strings"},
- {"empty_provider", "BAAI/bge-small-en-v1.5@", "Both model_name and provider must be non-empty strings"},
- {"whitespace_model_name", " @Builtin", "Both model_name and provider must be non-empty strings"},
- {"whitespace_provider", "BAAI/bge-small-en-v1.5@ ", "Both model_name and provider must be non-empty strings"},
+ {"empty", "", "embedding model identifier must follow <model_name>@<provider> format"},
+ {"whitespace", " ", "embedding model identifier must follow <model_name>@<provider> format"},
+ {"missing_at", "BAAI/bge-small-en-v1.5Builtin", "embedding model identifier must follow <model_name>@<provider> format"},
+ {"empty_model_name", "@Builtin", "both model_name and provider must be non-empty strings"},
+ {"empty_provider", "BAAI/bge-small-en-v1.5@", "both model_name and provider must be non-empty strings"},
+ {"whitespace_model_name", " @Builtin", "both model_name and provider must be non-empty strings"},
+ {"whitespace_provider", "BAAI/bge-small-en-v1.5@ ", "both model_name and provider must be non-empty strings"},
}
ctx := t.Context()
diff --git a/internal/service/dataset/crud.go b/internal/service/dataset/crud.go
index c82c650ceb..e910303a6a 100644
--- a/internal/service/dataset/crud.go
+++ b/internal/service/dataset/crud.go
@@ -23,7 +23,7 @@ func (d *DatasetService) CreateDataset(ctx context.Context, req *service.CreateD
name := strings.TrimSpace(req.Name)
if name == "" {
- return nil, common.CodeDataError, errors.New("Dataset name can't be empty.")
+ return nil, common.CodeDataError, errors.New("dataset name can't be empty")
}
if len(name) > entity.DatasetNameLimit {
return nil, common.CodeDataError, fmt.Errorf("Dataset name length is %d which is large than %d", len(name), entity.DatasetNameLimit)
@@ -74,20 +74,20 @@ func (d *DatasetService) CreateDataset(ctx context.Context, req *service.CreateD
}
if req.EmbeddingModel != nil {
embeddingModel = strings.TrimSpace(*req.EmbeddingModel)
- if err := validateDatasetEmbeddingModel(embeddingModel); err != nil {
+ if err = validateDatasetEmbeddingModel(embeddingModel); err != nil {
return nil, common.CodeDataError, err
}
}
if pipelineID != nil && strings.TrimSpace(*pipelineID) != "" {
- if ok, err := canvasAccessibleForUser(tenantID, strings.TrimSpace(*pipelineID)); err != nil {
+ if ok, err := canvasAccessibleForUser(ctx, tenantID, strings.TrimSpace(*pipelineID)); err != nil {
return nil, common.CodeServerError, err
} else if !ok {
return nil, common.CodeDataError, errors.New("canvas is not accessible")
}
}
- parserConfig, cpErr := service.ResolveComponentParamsDefaults(parserID, pipelineID)
+ parserConfig, cpErr := service.ResolveComponentParamsDefaults(ctx, parserID, pipelineID)
if cpErr != nil {
common.Warn("failed to resolve component params defaults for dataset",
zap.String("parserID", parserID), zap.Error(cpErr))
diff --git a/internal/service/dataset/helpers.go b/internal/service/dataset/helpers.go
index 21b937ac83..db41589c94 100644
--- a/internal/service/dataset/helpers.go
+++ b/internal/service/dataset/helpers.go
@@ -1,6 +1,7 @@
package dataset
import (
+ "context"
"encoding/json"
"errors"
"fmt"
@@ -70,9 +71,9 @@ func parserIDError() error {
case 0:
return errors.New("invalid parser_id")
case 1:
- return fmt.Errorf("Input should be '%s'", refs[0])
+ return fmt.Errorf("input should be '%s'", refs[0])
default:
- return fmt.Errorf("Input should be %s or '%s'", quoteList(refs[:len(refs)-1]), refs[len(refs)-1])
+ return fmt.Errorf("input should be %s or '%s'", quoteList(refs[:len(refs)-1]), refs[len(refs)-1])
}
}
@@ -86,15 +87,15 @@ func quoteList(items []string) string {
func validateDatasetAvatar(avatar string) error {
if !strings.Contains(avatar, ",") {
- return errors.New("Missing MIME prefix. Expected format: data:<mime>;base64,<data>")
+ return errors.New("missing MIME prefix. Expected format: data:<mime>;base64,<data>")
}
prefix, _, _ := strings.Cut(avatar, ",")
if !strings.HasPrefix(prefix, "data:") {
- return errors.New("Invalid MIME prefix format. Must start with 'data:'")
+ return errors.New("invalid MIME prefix format. Must start with 'data:'")
}
mimeType, _, _ := strings.Cut(strings.TrimPrefix(prefix, "data:"), ";")
if _, ok := datasetSupportedAvatarMIMETypes[mimeType]; !ok {
- return errors.New("Unsupported MIME type. Allowed: [image/jpeg image/png]")
+ return errors.New("unsupported MIME type. Allowed: [image/jpeg image/png]")
}
return nil
}
@@ -117,15 +118,15 @@ func validateDatasetEmbeddingModel(embeddingModel string) error {
}
if !strings.Contains(embeddingModel, "@") {
- return errors.New("Embedding model identifier must follow <model_name>@<provider> format")
+ return errors.New("embedding model identifier must follow <model_name>@<provider> format")
}
parts := strings.SplitN(embeddingModel, "@", 2)
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
- return errors.New("Both model_name and provider must be non-empty strings")
+ return errors.New("both model_name and provider must be non-empty strings")
}
if strings.TrimSpace(parts[0]) == "" || strings.TrimSpace(parts[1]) == "" {
- return errors.New("Both model_name and provider must be non-empty strings")
+ return errors.New("both model_name and provider must be non-empty strings")
}
return nil
}
@@ -156,7 +157,7 @@ func validateDatasetParserConfigSize(parserConfig map[string]interface{}) error
return errors.New("parser_config must be valid JSON")
}
if len(data) > 65535 {
- return fmt.Errorf("Parser config exceeds size limit (max 65,535 characters). Current size: %d", len(data))
+ return fmt.Errorf("parser config exceeds size limit (max 65,535 characters). Current size: %d", len(data))
}
return nil
}
@@ -164,17 +165,17 @@ func validateDatasetParserConfigSize(parserConfig map[string]interface{}) error
func normalizeDatasetID(id string) (string, error) {
parsedUUID, err := uuid.Parse(id)
if err != nil {
- return "", errors.New("Invalid UUID format")
+ return "", errors.New("invalid UUID format")
}
if parsedUUID == (uuid.UUID{}) {
- return "", errors.New("Invalid UUID format")
+ return "", errors.New("invalid UUID format")
}
return strings.ReplaceAll(parsedUUID.String(), "-", ""), nil
}
-func canvasAccessibleForUser(userID, canvasID string) (bool, error) {
- tenantIDs, _ := dao.NewUserTenantDAO().GetTenantIDsByUserID(userID)
- return dao.NewUserCanvasDAO().Accessible(canvasID, userID, tenantIDs), nil
+func canvasAccessibleForUser(ctx context.Context, userID, canvasID string) (bool, error) {
+ tenantIDs, _ := dao.NewUserTenantDAO().GetTenantIDsByUserID(ctx, dao.DB, userID)
+ return dao.NewUserCanvasDAO().Accessible(ctx, dao.DB, canvasID, userID, tenantIDs), nil
}
func parserConfigValueOrEmptyList(parserConfig map[string]interface{}, key string) interface{} {
diff --git a/internal/service/dataset/metadata.go b/internal/service/dataset/metadata.go
index 88e0bbd351..a5e7676cdd 100644
--- a/internal/service/dataset/metadata.go
+++ b/internal/service/dataset/metadata.go
@@ -17,15 +17,15 @@ func (d *DatasetService) UpdateDocumentMetadataConfig(ctx context.Context, userI
userID = strings.TrimSpace(userID)
datasetID = strings.TrimSpace(datasetID)
if !d.Accessible(ctx, datasetID, userID) {
- return nil, common.CodeDataError, errors.New("You don't own the dataset.")
+ return nil, common.CodeDataError, errors.New("you don't own the dataset")
}
doc, err := d.documentDAO.GetByDocumentIDAndDatasetID(ctx, dao.DB, documentID, datasetID)
if err != nil {
if dao.IsNotFoundErr(err) {
- return nil, common.CodeDataError, fmt.Errorf("Document %s not found in dataset %s", documentID, datasetID)
+ return nil, common.CodeDataError, fmt.Errorf("document %s not found in dataset %s", documentID, datasetID)
}
- return nil, common.CodeServerError, errors.New("Database operation failed")
+ return nil, common.CodeServerError, errors.New("database operation failed")
}
metadata, ok := req["metadata"]
@@ -40,12 +40,12 @@ func (d *DatasetService) UpdateDocumentMetadataConfig(ctx context.Context, userI
parserConfig["metadata"] = metadata
if err = d.documentDAO.UpdateByID(ctx, dao.DB, doc.ID, map[string]interface{}{"parser_config": parserConfig}); err != nil {
- return nil, common.CodeServerError, errors.New("Database operation failed")
+ return nil, common.CodeServerError, errors.New("database operation failed")
}
doc, err = d.documentDAO.GetByID(ctx, dao.DB, doc.ID)
if err != nil {
- return nil, common.CodeServerError, errors.New("Database operation failed")
+ return nil, common.CodeServerError, errors.New("database operation failed")
}
return doc, common.CodeSuccess, nil
}
@@ -55,18 +55,18 @@ func (d *DatasetService) GetMetadataConfig(ctx context.Context, datasetID, tenan
datasetID = strings.TrimSpace(datasetID)
tenantID = strings.TrimSpace(tenantID)
if !d.Accessible(ctx, datasetID, tenantID) {
- return nil, common.CodeDataError, fmt.Errorf("User '%s' lacks permission for dataset '%s'", tenantID, datasetID)
+ return nil, common.CodeDataError, fmt.Errorf("user '%s' lacks permission for dataset '%s'", tenantID, datasetID)
}
kb, err := d.kbDAO.GetByID(ctx, dao.DB, datasetID)
if err != nil {
if dao.IsNotFoundErr(err) {
- return nil, common.CodeDataError, errors.New("Dataset not found")
+ return nil, common.CodeDataError, errors.New("dataset not found")
}
- return nil, common.CodeServerError, errors.New("Database operation failed")
+ return nil, common.CodeServerError, errors.New("database operation failed")
}
if kb == nil {
- return nil, common.CodeDataError, fmt.Errorf("User '%s' lacks permission for dataset '%s'", tenantID, datasetID)
+ return nil, common.CodeDataError, fmt.Errorf("user '%s' lacks permission for dataset '%s'", tenantID, datasetID)
}
return map[string]interface{}{
@@ -81,18 +81,18 @@ func (d *DatasetService) UpdateMetadataConfig(ctx context.Context, datasetID, te
tenantID = strings.TrimSpace(tenantID)
if !d.Accessible(ctx, datasetID, tenantID) {
- return nil, common.CodeDataError, fmt.Errorf("User '%s' lacks permission for dataset '%s'", tenantID, datasetID)
+ return nil, common.CodeDataError, fmt.Errorf("user '%s' lacks permission for dataset '%s'", tenantID, datasetID)
}
kb, err := d.kbDAO.GetByID(ctx, dao.DB, datasetID)
if err != nil {
if dao.IsNotFoundErr(err) {
- return nil, common.CodeDataError, errors.New("Dataset not found")
+ return nil, common.CodeDataError, errors.New("dataset not found")
}
- return nil, common.CodeServerError, errors.New("Database operation failed")
+ return nil, common.CodeServerError, errors.New("database operation failed")
}
if kb == nil {
- return nil, common.CodeDataError, fmt.Errorf("User '%s' lacks permission for dataset '%s'", tenantID, datasetID)
+ return nil, common.CodeDataError, fmt.Errorf("user '%s' lacks permission for dataset '%s'", tenantID, datasetID)
}
if req == nil {
@@ -116,7 +116,7 @@ func (d *DatasetService) UpdateMetadataConfig(ctx context.Context, datasetID, te
parserConfig["built_in_metadata"] = builtInMetadata
if err = d.kbDAO.UpdateByID(ctx, dao.DB, kb.ID, map[string]interface{}{"parser_config": parserConfig}); err != nil {
- return nil, common.CodeServerError, errors.New("Update auto-metadata error.(Database error)")
+ return nil, common.CodeServerError, errors.New("update auto-metadata error.(Database error)")
}
return map[string]interface{}{
diff --git a/internal/service/dataset/metadata_config_test.go b/internal/service/dataset/metadata_config_test.go
index 3c8f597559..5553d28461 100644
--- a/internal/service/dataset/metadata_config_test.go
+++ b/internal/service/dataset/metadata_config_test.go
@@ -172,7 +172,7 @@ func TestDatasetServiceUpdateDocumentMetadataConfigRejectsNonOwner(t *testing.T)
if code != common.CodeDataError {
t.Fatalf("expected data error code, got %d", code)
}
- if err.Error() != "You don't own the dataset." {
+ if err.Error() != "you don't own the dataset" {
t.Fatalf("unexpected error: %v", err)
}
}
diff --git a/internal/service/dataset/tags.go b/internal/service/dataset/tags.go
index 77bb70487f..8d41b0860d 100644
--- a/internal/service/dataset/tags.go
+++ b/internal/service/dataset/tags.go
@@ -107,7 +107,7 @@ func (d *DatasetService) ListTags(ctx context.Context, datasetID, userID string)
}
datasetID = normalizedID
if !d.kbDAO.Accessible(ctx, dao.DB, datasetID, userID) {
- return nil, common.CodeDataError, errors.New("No authorization.")
+ return nil, common.CodeDataError, errors.New("no authorization")
}
if d.docEngine == nil {
return nil, common.CodeServerError, errors.New("Document engine is not initialized")
@@ -200,7 +200,7 @@ func (d *DatasetService) RenameTag(ctx context.Context, datasetID, userID, fromT
return nil, common.CodeDataError, errors.New("Lack of \"Dataset ID\"")
}
if !d.kbDAO.Accessible(ctx, dao.DB, datasetID, userID) {
- return nil, common.CodeDataError, errors.New("No authorization.")
+ return nil, common.CodeDataError, errors.New("no authorization")
}
if d.docEngine == nil {
return nil, common.CodeServerError, errors.New("Document engine is not initialized")
diff --git a/internal/service/dataset/tags_list_test.go b/internal/service/dataset/tags_list_test.go
index da36503fb1..c18aa2989c 100644
--- a/internal/service/dataset/tags_list_test.go
+++ b/internal/service/dataset/tags_list_test.go
@@ -213,8 +213,8 @@ func TestDatasetServiceListTagsRejectsUnauthorizedDataset(t *testing.T) {
if code != common.CodeDataError {
t.Fatalf("code=%d want=%d", code, common.CodeDataError)
}
- if err.Error() != "No authorization." {
- t.Fatalf("error=%q want=%q", err.Error(), "No authorization.")
+ if err.Error() != "no authorization" {
+ t.Fatalf("error=%q want=%q", err.Error(), "no authorization")
}
}
diff --git a/internal/service/dataset/tags_rename_test.go b/internal/service/dataset/tags_rename_test.go
index 47199b7d20..033aac38e3 100644
--- a/internal/service/dataset/tags_rename_test.go
+++ b/internal/service/dataset/tags_rename_test.go
@@ -131,8 +131,8 @@ func TestDatasetServiceRenameTagUnauthorized(t *testing.T) {
if code != common.CodeDataError {
t.Fatalf("code=%d want=%d", code, common.CodeDataError)
}
- if err.Error() != "No authorization." {
- t.Fatalf("error=%q want=%q", err.Error(), "No authorization.")
+ if err.Error() != "no authorization" {
+ t.Fatalf("error=%q want=%q", err.Error(), "no authorization")
}
}
diff --git a/internal/service/dataset/update.go b/internal/service/dataset/update.go
index e2934f41df..57831eea9a 100644
--- a/internal/service/dataset/update.go
+++ b/internal/service/dataset/update.go
@@ -235,7 +235,7 @@ func (d *DatasetService) UpdateDataset(ctx context.Context, datasetID, tenantID
isPipeline, effParserID, effPipelineID := service.ResolveParseMode(
req.ParseType, req.ParserID, req.PipelineID,
service.ParseModeState{ParserID: lockedKB.ParserID, PipelineID: lockedKB.PipelineID})
- dslJSON, dslErr := service.LoadPipelineDSL(isPipeline, effParserID, effPipelineID)
+ dslJSON, dslErr := service.LoadPipelineDSL(ctx, isPipeline, effParserID, effPipelineID)
if dslErr != nil {
common.Warn("failed to load pipeline DSL for building parser_config",
zap.String("parserID", effParserID), zap.Error(dslErr))
@@ -257,7 +257,7 @@ func (d *DatasetService) UpdateDataset(ctx context.Context, datasetID, tenantID
}
if parserIDProvided && parserID != lockedKB.ParserID {
if _, ok := updates["parser_config"]; !ok {
- if resolved, cpErr := service.ResolveComponentParamsDefaults(parserID, nil); cpErr != nil {
+ if resolved, cpErr := service.ResolveComponentParamsDefaults(ctx, parserID, nil); cpErr != nil {
common.Warn("failed to resolve component params defaults on parser_id switch",
zap.String("parserID", parserID), zap.Error(cpErr))
} else if resolved != nil {
@@ -277,7 +277,7 @@ func (d *DatasetService) UpdateDataset(ctx context.Context, datasetID, tenantID
if parserIDProvided {
cfgParserID = parserID
}
- if cpDefaults, cpErr := service.ResolveComponentParamsDefaults(cfgParserID, pipelineID); cpErr != nil {
+ if cpDefaults, cpErr := service.ResolveComponentParamsDefaults(ctx, cfgParserID, pipelineID); cpErr != nil {
common.Warn("failed to resolve component params defaults on pipeline change",
zap.String("parserID", cfgParserID), zap.Error(cpErr))
} else if cpDefaults != nil {
diff --git a/internal/service/dataset/update_test.go b/internal/service/dataset/update_test.go
index caa14ec33b..3fbeb8dc8e 100644
--- a/internal/service/dataset/update_test.go
+++ b/internal/service/dataset/update_test.go
@@ -592,11 +592,11 @@ func TestDatasetServiceUpdateDatasetRejectsInvalidEmbeddingModelFormat(t *testin
embeddingModel string
expectedMessage string
}{
- {"empty", "", "Embedding model identifier must follow <model_name>@<provider> format"},
- {"whitespace", " ", "Embedding model identifier must follow <model_name>@<provider> format"},
- {"missing_at", "BAAI/bge-small-en-v1.5Builtin", "Embedding model identifier must follow <model_name>@<provider> format"},
- {"empty_model_name", "@Builtin", "Both model_name and provider must be non-empty strings"},
- {"empty_provider", "BAAI/bge-small-en-v1.5@", "Both model_name and provider must be non-empty strings"},
+ {"empty", "", "embedding model identifier must follow <model_name>@<provider> format"},
+ {"whitespace", " ", "embedding model identifier must follow <model_name>@<provider> format"},
+ {"missing_at", "BAAI/bge-small-en-v1.5Builtin", "embedding model identifier must follow <model_name>@<provider> format"},
+ {"empty_model_name", "@Builtin", "both model_name and provider must be non-empty strings"},
+ {"empty_provider", "BAAI/bge-small-en-v1.5@", "both model_name and provider must be non-empty strings"},
}
ctx := t.Context()
diff --git a/internal/service/document/document_artifact.go b/internal/service/document/document_artifact.go
index 7240618d84..7a320e5f4e 100644
--- a/internal/service/document/document_artifact.go
+++ b/internal/service/document/document_artifact.go
@@ -17,7 +17,7 @@ import (
func (s *DocumentService) GetDocumentImage(ctx context.Context, imageID string) ([]byte, error) {
parts := strings.SplitN(imageID, "-", 2)
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
- return nil, fmt.Errorf("Image not found.")
+ return nil, fmt.Errorf("image not found")
}
storageImpl := storage.GetStorageFactory().GetStorage()
@@ -49,7 +49,7 @@ func (s *DocumentService) GetDocumentArtifact(ctx context.Context, filename, use
return nil, ErrArtifactInvalidFileType
}
- if !s.sandboxArtifactAccessible(basename, userID) {
+ if !s.sandboxArtifactAccessible(ctx, basename, userID) {
// Same error as "object does not exist" to avoid leaking
// whether the artifact exists for a different user/agent.
return nil, ErrArtifactNotFound
@@ -92,7 +92,7 @@ func (s *DocumentService) GetDocumentArtifact(ctx context.Context, filename, use
// `LIKE '%...%'` which is fine here because the storage path is
// short and indexed lookup on (user_id, exp_user_id) keeps the
// scan narrow.
-func (s *DocumentService) sandboxArtifactDialogIDsForUser(filename, userID string) []string {
+func (s *DocumentService) sandboxArtifactDialogIDsForUser(ctx context.Context, filename, userID string) []string {
if filename == "" || userID == "" {
return nil
}
@@ -114,7 +114,7 @@ func (s *DocumentService) sandboxArtifactDialogIDsForUser(filename, userID strin
filenamePattern := "%" + filenameSafe + "%"
artifactRefPattern := "%" + artifactRefSafe + "%"
dialogIDs := make(map[string]struct{})
- rows, err := dao.DB.Model(&entity.API4Conversation{}).
+ rows, err := dao.DB.WithContext(ctx).Model(&entity.API4Conversation{}).
Select("dialog_id").
Where("user_id = ? OR exp_user_id = ?", userID, userID).
Where(`message LIKE ? ESCAPE '!' OR message LIKE ? ESCAPE '!'`,
@@ -127,7 +127,7 @@ func (s *DocumentService) sandboxArtifactDialogIDsForUser(filename, userID strin
defer rows.Close()
for rows.Next() {
var d string
- if err := rows.Scan(&d); err == nil && d != "" {
+ if err = rows.Scan(&d); err == nil && d != "" {
dialogIDs[d] = struct{}{}
}
}
@@ -145,7 +145,7 @@ func (s *DocumentService) sandboxArtifactDialogIDsForUser(filename, userID strin
// UserCanvasDAO.Accessible (owner or team permission, with the
// latter scoped to the caller's tenant membership — PR review
// round 5).
-func (s *DocumentService) sandboxArtifactAccessible(filename, userID string) bool {
+func (s *DocumentService) sandboxArtifactAccessible(ctx context.Context, filename, userID string) bool {
if userID == "" {
return false
}
@@ -155,12 +155,12 @@ func (s *DocumentService) sandboxArtifactAccessible(filename, userID string) boo
// (callers without tenant data) is safe — it effectively disables
// the team branch, so the only matches are canvases the caller
// directly owns.
- tenantIDs, terr := dao.NewUserTenantDAO().GetTenantIDsByUserID(userID)
+ tenantIDs, terr := dao.NewUserTenantDAO().GetTenantIDsByUserID(ctx, dao.DB, userID)
if terr != nil {
tenantIDs = nil
}
- for _, dialogID := range s.sandboxArtifactDialogIDsForUser(filename, userID) {
- if s.canvasDAO.Accessible(dialogID, userID, tenantIDs) {
+ for _, dialogID := range s.sandboxArtifactDialogIDsForUser(ctx, filename, userID) {
+ if s.canvasDAO.Accessible(ctx, dao.DB, dialogID, userID, tenantIDs) {
return true
}
}
diff --git a/internal/service/document/document_dataset_update.go b/internal/service/document/document_dataset_update.go
index 69df41b799..6823d762d4 100644
--- a/internal/service/document/document_dataset_update.go
+++ b/internal/service/document/document_dataset_update.go
@@ -22,7 +22,7 @@ import (
func (s *DocumentService) BatchUpdateDocumentStatus(ctx context.Context, userID, datasetID, status string, documentIDs []string) (map[string]interface{}, common.ErrorCode, error) {
kb, err := s.kbDAO.GetByIDAndTenantID(ctx, dao.DB, datasetID, userID)
if err != nil {
- return nil, common.CodeDataError, fmt.Errorf("You don't own the dataset.")
+ return nil, common.CodeDataError, fmt.Errorf("you don't own the dataset")
}
statusInt, convErr := strconv.Atoi(status)
if convErr != nil {
@@ -113,7 +113,7 @@ func (s *DocumentService) UpdateDatasetDocument(ctx context.Context, userID, dat
kb, err := s.kbDAO.GetByIDAndTenantID(ctx, dao.DB, datasetID, tenantID)
if err != nil {
if dao.IsNotFoundErr(err) {
- return nil, common.CodeDataError, errors.New("You don't own the dataset.")
+ return nil, common.CodeDataError, errors.New("you don't own the dataset")
}
return nil, common.CodeDataError, errors.New("can't find this dataset")
}
@@ -121,7 +121,7 @@ func (s *DocumentService) UpdateDatasetDocument(ctx context.Context, userID, dat
doc, err := s.documentDAO.GetByDocumentIDAndDatasetID(ctx, dao.DB, documentID, datasetID)
if err != nil {
if dao.IsNotFoundErr(err) {
- return nil, common.CodeDataError, errors.New("The dataset doesn't own the document.")
+ return nil, common.CodeDataError, errors.New("the dataset doesn't own the document")
}
return nil, common.CodeServerError, err
}
@@ -157,7 +157,7 @@ func (s *DocumentService) UpdateDatasetDocument(ctx context.Context, userID, dat
return nil, common.CodeDataError, err
}
var dslJSON []byte
- dslJSON, err = service.LoadPipelineDSL(isPipeline, effParserID, effPipelineID)
+ dslJSON, err = service.LoadPipelineDSL(ctx, isPipeline, effParserID, effPipelineID)
if err != nil {
common.Warn("cleanAndUpdateDocumentParserConfig: failed to load DSL, falling back to merge",
zap.Error(err))
diff --git a/internal/service/document/document_list.go b/internal/service/document/document_list.go
index 85a9b34de0..58e8382bad 100644
--- a/internal/service/document/document_list.go
+++ b/internal/service/document/document_list.go
@@ -44,7 +44,7 @@ func (s *DocumentService) GetThumbnails(ctx context.Context, userID string, docI
tenantIDs := []string{userID}
if userID != "" {
- ids, err := dao.NewUserTenantDAO().GetTenantIDsByUserID(userID)
+ ids, err := dao.NewUserTenantDAO().GetTenantIDsByUserID(ctx, dao.DB, userID)
if err != nil {
return nil, fmt.Errorf("failed to fetch user tenants: %w", err)
}
diff --git a/internal/service/document/document_test.go b/internal/service/document/document_test.go
index 06665a5086..19b97eed43 100644
--- a/internal/service/document/document_test.go
+++ b/internal/service/document/document_test.go
@@ -1620,7 +1620,7 @@ func TestUpdateDatasetDocumentRejectsNonOwner(t *testing.T) {
if code != common.CodeDataError {
t.Fatalf("code = %v, want %v", code, common.CodeDataError)
}
- if err.Error() != "You don't own the dataset." {
+ if err.Error() != "you don't own the dataset" {
t.Fatalf("err = %q", err.Error())
}
}
diff --git a/internal/service/document/file2document.go b/internal/service/document/file2document.go
index 4cdcd3ff95..c25faf7b20 100644
--- a/internal/service/document/file2document.go
+++ b/internal/service/document/file2document.go
@@ -40,8 +40,8 @@ var (
ErrLinkFileNotFound = errors.New("File not found!")
// ErrLinkDatasetNotFound mirrors Python "Can't find this dataset!".
ErrLinkDatasetNotFound = errors.New("Can't find this dataset!")
- // ErrLinkNoAuthorization mirrors Python "No authorization.".
- ErrLinkNoAuthorization = errors.New("No authorization.")
+ // ErrLinkNoAuthorization mirrors Python "no authorization".
+ ErrLinkNoAuthorization = errors.New("no authorization")
// ErrLinkInternal is a generic, safe-to-expose internal failure.
ErrLinkInternal = errors.New("Internal server error.")
)
diff --git a/internal/service/file/file_content.go b/internal/service/file/file_content.go
index 20e094b64c..56af088322 100644
--- a/internal/service/file/file_content.go
+++ b/internal/service/file/file_content.go
@@ -21,7 +21,7 @@ func (s *FileService) GetFileContent(ctx context.Context, uid, fileID string) (*
return nil, fmt.Errorf("Document not found!")
}
if !s.checkFilePerm(ctx, s.fileDAO, file, uid) {
- return nil, fmt.Errorf("No authorization.")
+ return nil, fmt.Errorf("no authorization")
}
return file, nil
}
@@ -129,7 +129,7 @@ func (s *FileService) GetFileContents(ctx context.Context, uid string, fileDicts
}
// Permission: only the owner can access their uploads bucket.
if createdBy != uid {
- return nil, nil, fmt.Errorf("No authorization.")
+ return nil, nil, fmt.Errorf("no authorization")
}
data, derr := storageImpl.Get(createdBy+"-downloads", id)
diff --git a/internal/service/file/file_delete.go b/internal/service/file/file_delete.go
index 2a14fa6ac5..0fef740e1d 100644
--- a/internal/service/file/file_delete.go
+++ b/internal/service/file/file_delete.go
@@ -32,7 +32,7 @@ func (s *FileService) DeleteFiles(ctx context.Context, uid string, fileIDs []str
// 3. Permission check
if !s.checkFilePerm(ctx, s.fileDAO, file, uid) {
- return false, "No authorization."
+ return false, "no authorization"
}
// 4. Skip dataset source files
diff --git a/internal/service/file/file_test.go b/internal/service/file/file_test.go
index c30aa63541..065a3786e3 100644
--- a/internal/service/file/file_test.go
+++ b/internal/service/file/file_test.go
@@ -118,7 +118,7 @@ func TestFileService_GetFileContents_NotAccessible(t *testing.T) {
if err == nil {
t.Fatal("expected authorization error")
}
- if err.Error() != "No authorization." {
+ if err.Error() != "no authorization" {
t.Fatalf("unexpected error: %v", err)
}
if len(texts) != 0 || len(images) != 0 {
diff --git a/internal/service/ingestion_task_service.go b/internal/service/ingestion_task_service.go
index b921ce7925..950b3310f6 100644
--- a/internal/service/ingestion_task_service.go
+++ b/internal/service/ingestion_task_service.go
@@ -166,7 +166,7 @@ func (s *IngestionTaskService) ListAllForAdmin(ctx context.Context) ([]map[strin
showTasks := make([]map[string]interface{}, 0, len(ingestionTasks))
for _, task := range ingestionTasks {
var user *entity.User
- user, err = s.userDAO.GetByTenantID(task.UserID)
+ user, err = s.userDAO.GetByTenantID(ctx, dao.DB, task.UserID)
if err != nil {
return nil, err
}
diff --git a/internal/service/model_service.go b/internal/service/model_service.go
index 0eaf31bcf2..a2bfa8eb85 100644
--- a/internal/service/model_service.go
+++ b/internal/service/model_service.go
@@ -169,7 +169,7 @@ type CheckConnectionRequest struct {
func (m *ModelProviderService) AddModelProvider(ctx context.Context, providerName, userID string) (common.ErrorCode, error) {
providerName = strings.TrimSpace(providerName)
- tenants, err := m.userTenantDAO.GetByUserIDAndRole(userID, "owner")
+ tenants, err := m.userTenantDAO.GetByUserIDAndRole(ctx, dao.DB, userID, "owner")
if err != nil {
return common.CodeServerError, err
}
@@ -204,7 +204,7 @@ func (m *ModelProviderService) AddModelProvider(ctx context.Context, providerNam
func (m *ModelProviderService) ListProvidersOfTenant(ctx context.Context, userID string) ([]map[string]interface{}, common.ErrorCode, error) {
- tenants, err := m.userTenantDAO.GetByUserIDAndRole(userID, "owner")
+ tenants, err := m.userTenantDAO.GetByUserIDAndRole(ctx, dao.DB, userID, "owner")
if err != nil {
return nil, common.CodeServerError, err
}
@@ -284,7 +284,7 @@ func isExcludedTenantProvider(name string) bool {
}
func (m *ModelProviderService) DeleteModelProvider(ctx context.Context, userID, providerName string) (common.ErrorCode, error) {
- tenants, err := m.userTenantDAO.GetByUserIDAndRole(userID, "owner")
+ tenants, err := m.userTenantDAO.GetByUserIDAndRole(ctx, dao.DB, userID, "owner")
if err != nil {
return common.CodeServerError, err
}
@@ -329,7 +329,7 @@ func (m *ModelProviderService) ListSupportedModels(ctx context.Context, provider
providerName = strings.TrimSpace(providerName)
// Get tenant ID from user
- tenants, err := m.userTenantDAO.GetByUserIDAndRole(userID, "owner")
+ tenants, err := m.userTenantDAO.GetByUserIDAndRole(ctx, dao.DB, userID, "owner")
if err != nil {
return nil, errors.New("fail to get tenant")
}
@@ -419,7 +419,7 @@ func (m *ModelProviderService) CreateProviderInstance(ctx context.Context, provi
providerIDOrName = strings.TrimSpace(providerIDOrName)
// Get tenant ID from user
- tenants, err := m.userTenantDAO.GetByUserIDAndRole(userID, "owner")
+ tenants, err := m.userTenantDAO.GetByUserIDAndRole(ctx, dao.DB, userID, "owner")
if err != nil {
return common.CodeServerError, err
}
@@ -538,7 +538,7 @@ func (m *ModelProviderService) CreateNameOnlyProviderInstance(ctx context.Contex
return common.CodeBadRequest, errors.New("instance name cannot be 'default'")
}
- tenants, err := m.userTenantDAO.GetByUserIDAndRole(userID, "owner")
+ tenants, err := m.userTenantDAO.GetByUserIDAndRole(ctx, dao.DB, userID, "owner")
if err != nil {
return common.CodeServerError, err
}
@@ -685,7 +685,7 @@ func (m *ModelProviderService) ListProviderInstances(ctx context.Context, provid
providerIDOrName = strings.TrimSpace(providerIDOrName)
// Get tenant ID from user
- tenants, err := m.userTenantDAO.GetByUserIDAndRole(userID, "owner")
+ tenants, err := m.userTenantDAO.GetByUserIDAndRole(ctx, dao.DB, userID, "owner")
if err != nil {
return nil, common.CodeServerError, err
}
@@ -746,7 +746,7 @@ func (m *ModelProviderService) ShowProviderInstance(ctx context.Context, provide
providerName = strings.ToLower(providerName)
// Get tenant ID from user
- tenants, err := m.userTenantDAO.GetByUserIDAndRole(userID, "owner")
+ tenants, err := m.userTenantDAO.GetByUserIDAndRole(ctx, dao.DB, userID, "owner")
if err != nil {
return nil, common.CodeServerError, err
}
@@ -809,7 +809,7 @@ func (m *ModelProviderService) ShowProviderInstance(ctx context.Context, provide
func (m *ModelProviderService) ShowInstanceBalance(ctx context.Context, providerName, instanceName, userID string) (map[string]interface{}, common.ErrorCode, error) {
// Get tenant ID from user
- tenants, err := m.userTenantDAO.GetByUserIDAndRole(userID, "owner")
+ tenants, err := m.userTenantDAO.GetByUserIDAndRole(ctx, dao.DB, userID, "owner")
if err != nil {
return nil, common.CodeServerError, err
}
@@ -919,7 +919,7 @@ func (m *ModelProviderService) CheckConnection(ctx context.Context, providerName
// present in the request body.
func (m *ModelProviderService) updateModelVerifyResults(ctx context.Context, userID, providerName, instanceID string, modelVerifyResult map[string]string) error {
// Resolve tenant from user.
- userTenants, err := m.userTenantDAO.GetByUserID(userID)
+ userTenants, err := m.userTenantDAO.GetByUserID(ctx, dao.DB, userID)
if err != nil || len(userTenants) == 0 {
return fmt.Errorf("no tenant found for user %s", userID)
}
@@ -1224,7 +1224,7 @@ func minimalPNG() []byte {
func (m *ModelProviderService) CheckInstanceConnection(ctx context.Context, providerName, instanceName, userID string) (common.ErrorCode, error) {
// Get tenant ID from user
- tenants, err := m.userTenantDAO.GetByUserIDAndRole(userID, "owner")
+ tenants, err := m.userTenantDAO.GetByUserIDAndRole(ctx, dao.DB, userID, "owner")
if err != nil {
return common.CodeServerError, err
}
@@ -1284,7 +1284,7 @@ func (m *ModelProviderService) CheckInstanceConnection(ctx context.Context, prov
func (m *ModelProviderService) ListTasks(ctx context.Context, providerName, instanceName, userID string) ([]modelModule.ListTaskStatus, common.ErrorCode, error) {
// Get tenant ID from user
- tenants, err := m.userTenantDAO.GetByUserIDAndRole(userID, "owner")
+ tenants, err := m.userTenantDAO.GetByUserIDAndRole(ctx, dao.DB, userID, "owner")
if err != nil {
return nil, common.CodeServerError, err
}
@@ -1345,7 +1345,7 @@ func (m *ModelProviderService) ListTasks(ctx context.Context, providerName, inst
func (m *ModelProviderService) ShowTask(ctx context.Context, providerName, instanceName, taskID, userID string) (*modelModule.TaskResponse, common.ErrorCode, error) {
// Get tenant ID from user
- tenants, err := m.userTenantDAO.GetByUserIDAndRole(userID, "owner")
+ tenants, err := m.userTenantDAO.GetByUserIDAndRole(ctx, dao.DB, userID, "owner")
if err != nil {
return nil, common.CodeServerError, err
}
@@ -1637,7 +1637,7 @@ func (m *ModelProviderService) ListTenantAddedModels(ctx context.Context, userID
func (m *ModelProviderService) resolveModelListTenant(ctx context.Context, userID, ownerTenantID string) (*entity.Tenant, common.ErrorCode, error) {
if ownerTenantID == "" {
- tenants, err := m.userTenantDAO.GetByUserIDAndRole(userID, "owner")
+ tenants, err := m.userTenantDAO.GetByUserIDAndRole(ctx, dao.DB, userID, "owner")
if err != nil {
return nil, common.CodeServerError, err
}
@@ -1646,7 +1646,7 @@ func (m *ModelProviderService) resolveModelListTenant(ctx context.Context, userI
}
ownerTenantID = tenants[0].TenantID
} else {
- relations, err := m.userTenantDAO.GetByUserID(userID)
+ relations, err := m.userTenantDAO.GetByUserID(ctx, dao.DB, userID)
if err != nil {
return nil, common.CodeServerError, err
}
@@ -1838,7 +1838,7 @@ func (m *ModelProviderService) ensureOCRProviderFromEnv(ctx context.Context, ten
func (m *ModelProviderService) AlterProviderInstance(ctx context.Context, userID, providerIDOrName, instanceIDOrName, newInstanceName, apiKey, baseURL, region string, modelInfo []CreateInstanceModelInfo, verify bool) (common.ErrorCode, error) {
providerIDOrName = strings.TrimSpace(providerIDOrName)
- tenants, err := m.userTenantDAO.GetByUserIDAndRole(userID, "owner")
+ tenants, err := m.userTenantDAO.GetByUserIDAndRole(ctx, dao.DB, userID, "owner")
if err != nil {
return common.CodeServerError, err
}
@@ -2011,7 +2011,7 @@ func (m *ModelProviderService) DropProviderInstances(ctx context.Context, provid
}
// Get tenant ID from user
- tenants, err := m.userTenantDAO.GetByUserIDAndRole(userID, "owner")
+ tenants, err := m.userTenantDAO.GetByUserIDAndRole(ctx, dao.DB, userID, "owner")
if err != nil {
return common.CodeServerError, err
}
@@ -2080,7 +2080,7 @@ func (m *ModelProviderService) DropProviderInstances(ctx context.Context, provid
func (m *ModelProviderService) DropInstanceModels(ctx context.Context, providerIDOrName, instanceIDOrName, userID string, modelNames []string) (common.ErrorCode, error) {
// Get tenant ID from user
- tenants, err := m.userTenantDAO.GetByUserIDAndRole(userID, "owner")
+ tenants, err := m.userTenantDAO.GetByUserIDAndRole(ctx, dao.DB, userID, "owner")
if err != nil {
return common.CodeServerError, err
}
@@ -2148,7 +2148,7 @@ func (m *ModelProviderService) DropInstanceModels(ctx context.Context, providerI
func (m *ModelProviderService) ListInstanceModels(ctx context.Context, providerName, instanceName, userID string) ([]map[string]interface{}, error) {
// Get tenant ID from user
- tenants, err := m.userTenantDAO.GetByUserIDAndRole(userID, "owner")
+ tenants, err := m.userTenantDAO.GetByUserIDAndRole(ctx, dao.DB, userID, "owner")
if err != nil {
return nil, err
}
@@ -2243,7 +2243,7 @@ func (m *ModelProviderService) AlterModel(ctx context.Context, providerName, ins
}
// Get tenant ID from user
- tenants, err := m.userTenantDAO.GetByUserIDAndRole(userID, "owner")
+ tenants, err := m.userTenantDAO.GetByUserIDAndRole(ctx, dao.DB, userID, "owner")
if err != nil {
return common.CodeServerError, err
}
@@ -2456,7 +2456,7 @@ func maxTokensFromTenantModelExtra(modelEntity *entity.TenantModel, fallback int
func (m *ModelProviderService) getModelInstanceAndProviderByName(ctx context.Context, providerName, instanceName, modelName *string, userID string, apiConfig *modelModule.APIConfig) (*ModelInstanceAndProviderInfo, error) {
// Get tenant ID from user
- tenants, err := m.userTenantDAO.GetByUserIDAndRole(userID, "owner")
+ tenants, err := m.userTenantDAO.GetByUserIDAndRole(ctx, dao.DB, userID, "owner")
if err != nil {
return nil, err
}
@@ -2529,7 +2529,7 @@ func (m *ModelProviderService) getModelInstanceAndProviderByName(ctx context.Con
func (m *ModelProviderService) getModelInstanceAndProviderByID(ctx context.Context, modelID *string, userID string, apiConfig *modelModule.APIConfig) (*ModelInstanceAndProviderInfo, error) {
// Get tenant ID from user
- tenants, err := m.userTenantDAO.GetByUserIDAndRole(userID, "owner")
+ tenants, err := m.userTenantDAO.GetByUserIDAndRole(ctx, dao.DB, userID, "owner")
if err != nil {
return nil, err
}
@@ -3584,7 +3584,7 @@ func (m *ModelProviderService) AddModel(ctx context.Context, request *AddModelRe
return common.CodeBadRequest, errors.New("model_type is required")
}
- tenants, err := m.userTenantDAO.GetByUserIDAndRole(userID, "owner")
+ tenants, err := m.userTenantDAO.GetByUserIDAndRole(ctx, dao.DB, userID, "owner")
if err != nil {
return common.CodeServerError, err
}
diff --git a/internal/service/oauth_login.go b/internal/service/oauth_login.go
index 0501b22199..54ec4e72fa 100644
--- a/internal/service/oauth_login.go
+++ b/internal/service/oauth_login.go
@@ -32,6 +32,8 @@ import (
"ragflow/internal/server"
"ragflow/internal/utility"
"ragflow/internal/utility/oauth"
+
+ "gorm.io/gorm"
)
// Sentinel errors surfaced by the OAuth login + callback endpoints. The
@@ -169,7 +171,7 @@ func (s *UserService) OAuthCallback(ctx context.Context, channel, code, callback
return nil, common.CodeDataError, ErrOAuthEmailMissing
}
- existing, err := s.userDAO.GetByEmail(info.Email)
+ existing, err := s.userDAO.GetByEmail(ctx, dao.DB, info.Email)
if err == nil && existing != nil {
if existing.IsActive == "0" {
return nil, common.CodeForbidden, ErrOAuthUserInactive
@@ -178,8 +180,8 @@ func (s *UserService) OAuthCallback(ctx context.Context, channel, code, callback
existing.AccessToken = &newToken
now := time.Now().Truncate(time.Second)
existing.LastLoginTime = &now
- if uerr := s.userDAO.Update(existing); uerr != nil {
- return nil, common.CodeServerError, fmt.Errorf("update user: %w", uerr)
+ if err = s.userDAO.Update(ctx, dao.DB, existing); err != nil {
+ return nil, common.CodeServerError, fmt.Errorf("update user: %w", err)
}
return &OAuthCallbackResult{User: existing, IsNewUser: false}, common.CodeSuccess, nil
}
@@ -260,24 +262,25 @@ func (s *UserService) registerOAuthUser(ctx context.Context, channel string, inf
userTenantDAO := dao.NewUserTenantDAO()
fileDAO := dao.NewFileDAO()
- if err := s.userDAO.Create(user); err != nil {
- return nil, common.CodeServerError, fmt.Errorf("Failed to register %s: %w", info.Email, err)
- }
- if err := tenantDAO.Create(ctx, dao.DB, tenant); err != nil {
- _ = s.userDAO.DeleteByID(userID)
- return nil, common.CodeServerError, fmt.Errorf("Failed to register %s: %w", info.Email, err)
- }
- if err := userTenantDAO.Create(userTenant); err != nil {
- _ = s.userDAO.DeleteByID(userID)
- _ = tenantDAO.Delete(ctx, dao.DB, userID)
- return nil, common.CodeServerError, fmt.Errorf("Failed to register %s: %w", info.Email, err)
- }
- if err := fileDAO.Create(ctx, dao.DB, rootFile); err != nil {
- _ = s.userDAO.DeleteByID(userID)
- _ = tenantDAO.Delete(ctx, dao.DB, userID)
- _ = userTenantDAO.Delete(userTenantID)
- return nil, common.CodeServerError, fmt.Errorf("Failed to register %s: %w", info.Email, err)
+ err := dao.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ if err := s.userDAO.Create(ctx, tx, user); err != nil {
+ return fmt.Errorf("failed to register %s: %w", info.Email, err)
+ }
+ if err := tenantDAO.Create(ctx, tx, tenant); err != nil {
+ return fmt.Errorf("failed to register %s: %w", info.Email, err)
+ }
+ if err := userTenantDAO.Create(ctx, tx, userTenant); err != nil {
+ return fmt.Errorf("failed to register %s: %w", info.Email, err)
+ }
+ if err := fileDAO.Create(ctx, tx, rootFile); err != nil {
+ return fmt.Errorf("failed to register %s: %w", info.Email, err)
+ }
+ return nil
+ })
+ if err != nil {
+ return nil, common.CodeServerError, err
}
+
return user, common.CodeSuccess, nil
}
diff --git a/internal/service/pipeline_params.go b/internal/service/pipeline_params.go
index dbfa34d7f1..9e05ba2095 100644
--- a/internal/service/pipeline_params.go
+++ b/internal/service/pipeline_params.go
@@ -1,6 +1,7 @@
package service
import (
+ "context"
"encoding/json"
"errors"
"fmt"
@@ -15,11 +16,11 @@ import (
// canvas's dsl column holds the same component-graph structure that built-in
// templates use, so it can be validated by the same schema extractor. It is a
// package-level function so both document and knowledge-base updates reuse it.
-func loadCanvasDSLJSON(canvasID string) ([]byte, error) {
+func loadCanvasDSLJSON(ctx context.Context, canvasID string) ([]byte, error) {
if strings.TrimSpace(canvasID) == "" {
return nil, fmt.Errorf("empty canvas id")
}
- canvas, err := dao.NewUserCanvasDAO().GetByID(canvasID)
+ canvas, err := dao.NewUserCanvasDAO().GetByID(ctx, dao.DB, canvasID)
if err != nil {
if errors.Is(err, dao.ErrUserCanvasNotFound) {
return nil, fmt.Errorf("canvas %s not found", canvasID)
@@ -39,9 +40,9 @@ func loadCanvasDSLJSON(canvasID string) ([]byte, error) {
// LoadPipelineDSL loads the DSL JSON for a pipeline identified by parserID
// (built-in) or pipelineID (custom canvas). When both are provided, isPipeline
// selects which one to use.
-func LoadPipelineDSL(isPipeline bool, parserID string, pipelineID *string) ([]byte, error) {
+func LoadPipelineDSL(ctx context.Context, isPipeline bool, parserID string, pipelineID *string) ([]byte, error) {
if isPipeline {
- return loadCanvasDSLJSON(strings.TrimSpace(*pipelineID))
+ return loadCanvasDSLJSON(ctx, strings.TrimSpace(*pipelineID))
}
registry, err := pipelinepkg.DefaultRegistry()
if err != nil {
@@ -61,12 +62,12 @@ func LoadPipelineDSL(isPipeline bool, parserID string, pipelineID *string) ([]by
// returns the component params defaults as an entity.JSONMap {cpnID: {param: value}}.
// For builtin templates the DSL is loaded from the embedded registry; for custom
// canvas pipelines it is loaded from the canvas row in the database.
-func ResolveComponentParamsDefaults(parserID string, pipelineID *string) (entity.JSONMap, error) {
+func ResolveComponentParamsDefaults(ctx context.Context, parserID string, pipelineID *string) (entity.JSONMap, error) {
isPipeline := pipelineID != nil && strings.TrimSpace(*pipelineID) != ""
var cp map[string]map[string]any
var err error
if isPipeline {
- dslJSON, lerr := loadCanvasDSLJSON(strings.TrimSpace(*pipelineID))
+ dslJSON, lerr := loadCanvasDSLJSON(ctx, strings.TrimSpace(*pipelineID))
if lerr != nil {
return nil, fmt.Errorf("load canvas DSL: %w", lerr)
}
diff --git a/internal/service/search.go b/internal/service/search.go
index 1ef5992ca8..6362cd2af6 100644
--- a/internal/service/search.go
+++ b/internal/service/search.go
@@ -91,7 +91,7 @@ func (s *SearchService) ListSearches(ctx context.Context, userID string, keyword
return nil, err
}
} else {
- ownerIDs, err = s.filterAccessibleSearchOwnerIDs(userID, ownerIDs)
+ ownerIDs, err = s.filterAccessibleSearchOwnerIDs(ctx, userID, ownerIDs)
if err != nil {
return nil, err
}
@@ -133,8 +133,8 @@ func (s *SearchService) ListSearches(ctx context.Context, userID string, keyword
}, nil
}
-func (s *SearchService) filterAccessibleSearchOwnerIDs(userID string, ownerIDs []string) ([]string, error) {
- tenantIDs, err := s.userTenantDAO.GetTenantIDsByUserID(userID)
+func (s *SearchService) filterAccessibleSearchOwnerIDs(ctx context.Context, userID string, ownerIDs []string) ([]string, error) {
+ tenantIDs, err := s.userTenantDAO.GetTenantIDsByUserID(ctx, dao.DB, userID)
if err != nil {
return nil, err
}
@@ -254,7 +254,7 @@ func (s *SearchService) CreateSearch(ctx context.Context, userID string, name st
func (s *SearchService) GetSearchDetail(ctx context.Context, userID string, searchID string) (*entity.Search, error) {
// Step 1: Get user tenants (same as Python UserTenantService.query(user_id=current_user.id))
- tenants, err := s.userTenantDAO.GetByUserID(userID)
+ tenants, err := s.userTenantDAO.GetByUserID(ctx, dao.DB, userID)
if err != nil {
return nil, fmt.Errorf("failed to get user tenants: %w", err)
}
@@ -283,7 +283,7 @@ func (s *SearchService) GetSearchDetail(ctx context.Context, userID string, sear
// Step 3: Get search detail (same as Python SearchService.get_detail(search_id))
search, err := s.searchDAO.GetByID(ctx, dao.DB, searchID)
if err != nil {
- return nil, fmt.Errorf("can't find this Search App!")
+ return nil, fmt.Errorf("can't find this Search App")
}
return search, nil
@@ -301,7 +301,7 @@ func (s *SearchService) GetSearchShareDetail(ctx context.Context, userID, search
return nil, err
}
if detail == nil {
- return nil, fmt.Errorf("can't find this Search App!")
+ return nil, fmt.Errorf("can't find this Search App")
}
return &SearchShareDetail{
@@ -311,7 +311,7 @@ func (s *SearchService) GetSearchShareDetail(ctx context.Context, userID, search
Name: detail.Name,
Description: detail.Description,
CreatedBy: detail.CreatedBy,
- SearchConfig: map[string]interface{}(detail.SearchConfig),
+ SearchConfig: detail.SearchConfig,
UpdateTime: detail.UpdateTime,
}, nil
}
diff --git a/internal/service/stats.go b/internal/service/stats.go
index 14750f5772..68385e2e01 100644
--- a/internal/service/stats.go
+++ b/internal/service/stats.go
@@ -52,7 +52,7 @@ type StatsResponse struct {
// GetStats returns daily API conversation statistics for the first tenant of a user.
func (s *StatsService) GetStats(ctx context.Context, userID, fromDate, toDate string, source *string) (*StatsResponse, error) {
- tenants, err := s.userTenantDAO.GetByUserID(userID)
+ tenants, err := s.userTenantDAO.GetByUserID(ctx, dao.DB, userID)
if err != nil || len(tenants) == 0 {
return nil, ErrTenantNotFound
}
diff --git a/internal/service/tenant.go b/internal/service/tenant.go
index 78e03315b4..a478081fbf 100644
--- a/internal/service/tenant.go
+++ b/internal/service/tenant.go
@@ -287,8 +287,8 @@ func (s *TenantLLMService) EnsureTenantModelIDForParams(ctx context.Context, ten
}
// GetTenantList get tenant list for a user
-func (s *TenantService) GetTenantList(userID string) ([]*TenantListItem, error) {
- tenants, err := s.userTenantDAO.GetTenantsByUserID(userID)
+func (s *TenantService) GetTenantList(ctx context.Context, userID string) ([]*TenantListItem, error) {
+ tenants, err := s.userTenantDAO.GetTenantsByUserID(ctx, dao.DB, userID)
if err != nil {
return nil, err
}
@@ -867,11 +867,11 @@ type TenantMemberResponse struct {
// ListMembers returns all non-owner members of tenantID.
// Only the tenant owner (userID == tenantID) may call this.
-func (s *TenantService) ListMembers(userID, tenantID string) ([]*TenantMemberResponse, common.ErrorCode, error) {
+func (s *TenantService) ListMembers(ctx context.Context, userID, tenantID string) ([]*TenantMemberResponse, common.ErrorCode, error) {
if userID != tenantID {
return nil, common.CodeAuthenticationError, fmt.Errorf("no authorization")
}
- rows, err := s.userTenantDAO.GetMembersByTenantID(tenantID)
+ rows, err := s.userTenantDAO.GetMembersByTenantID(ctx, dao.DB, tenantID)
if err != nil {
return nil, common.CodeServerError, err
}
@@ -912,7 +912,7 @@ type AddMemberResponse struct {
// AddMember invites a user (by email) to the tenant.
// Only the tenant owner (userID == tenantID) may call this.
-func (s *TenantService) AddMember(userID, tenantID string, req *AddMemberRequest) (*AddMemberResponse, common.ErrorCode, error) {
+func (s *TenantService) AddMember(ctx context.Context, userID, tenantID string, req *AddMemberRequest) (*AddMemberResponse, common.ErrorCode, error) {
if userID != tenantID {
return nil, common.CodeAuthenticationError, fmt.Errorf("no authorization")
}
@@ -920,13 +920,13 @@ func (s *TenantService) AddMember(userID, tenantID string, req *AddMemberRequest
return nil, common.CodeArgumentError, fmt.Errorf("email is required")
}
- invitee, err := s.userDAO.GetByEmail(req.Email)
+ invitee, err := s.userDAO.GetByEmail(ctx, dao.DB, req.Email)
if err != nil {
return nil, common.CodeDataError, fmt.Errorf("user not found")
}
// Reject if already a member or has a pending invitation.
- existing, _ := s.userTenantDAO.FilterByUserIDAndTenantID(invitee.ID, tenantID)
+ existing, _ := s.userTenantDAO.FilterByUserIDAndTenantID(ctx, dao.DB, invitee.ID, tenantID)
if existing != nil {
switch existing.Role {
case TenantRoleOwner:
@@ -947,7 +947,7 @@ func (s *TenantService) AddMember(userID, tenantID string, req *AddMemberRequest
InvitedBy: userID,
Status: &status,
}
- if err = s.userTenantDAO.Create(ut); err != nil {
+ if err = s.userTenantDAO.Create(ctx, dao.DB, ut); err != nil {
return nil, common.CodeServerError, fmt.Errorf("failed to create invitation: %w", err)
}
@@ -966,7 +966,7 @@ func (s *TenantService) AddMember(userID, tenantID string, req *AddMemberRequest
// RemoveMember removes a user from the tenant.
// Either the owner (userID == tenantID) or the member themselves (userID == targetUserID) may call this.
// The tenant owner (targetUserID == tenantID) cannot be removed.
-func (s *TenantService) RemoveMember(userID, tenantID, targetUserID string) (common.ErrorCode, error) {
+func (s *TenantService) RemoveMember(ctx context.Context, userID, tenantID, targetUserID string) (common.ErrorCode, error) {
if userID != tenantID && userID != targetUserID {
return common.CodeAuthenticationError, fmt.Errorf("no authorization")
}
@@ -976,25 +976,25 @@ func (s *TenantService) RemoveMember(userID, tenantID, targetUserID string) (com
if s.userTenantDAO == nil {
return common.CodeServerError, fmt.Errorf("userTenantDAO not initialized")
}
- if err := s.userTenantDAO.DeleteByUserAndTenant(targetUserID, tenantID); err != nil {
+ if err := s.userTenantDAO.DeleteByUserAndTenant(ctx, dao.DB, targetUserID, tenantID); err != nil {
return common.CodeServerError, fmt.Errorf("failed to remove member: %w", err)
}
return common.CodeSuccess, nil
}
// AcceptInvite transitions the calling user's role from "invite" → "normal" for the given tenant.
-func (s *TenantService) AcceptInvite(userID, tenantID string) (common.ErrorCode, error) {
+func (s *TenantService) AcceptInvite(ctx context.Context, userID, tenantID string) (common.ErrorCode, error) {
if s.userTenantDAO == nil {
return common.CodeServerError, fmt.Errorf("userTenantDAO not initialized")
}
- existing, err := s.userTenantDAO.FilterByUserIDAndTenantID(userID, tenantID)
+ existing, err := s.userTenantDAO.FilterByUserIDAndTenantID(ctx, dao.DB, userID, tenantID)
if err != nil || existing == nil {
return common.CodeDataError, fmt.Errorf("no pending invitation found")
}
if existing.Role != TenantRoleInvite {
return common.CodeArgumentError, fmt.Errorf("no pending invitation to accept")
}
- if err := s.userTenantDAO.UpdateRoleByUserAndTenant(userID, tenantID, TenantRoleNormal); err != nil {
+ if err := s.userTenantDAO.UpdateRoleByUserAndTenant(ctx, dao.DB, userID, tenantID, TenantRoleNormal); err != nil {
return common.CodeServerError, fmt.Errorf("failed to accept invitation: %w", err)
}
return common.CodeSuccess, nil
diff --git a/internal/service/tenant_test.go b/internal/service/tenant_test.go
index 5caaa2ad65..13b9205ff6 100644
--- a/internal/service/tenant_test.go
+++ b/internal/service/tenant_test.go
@@ -36,7 +36,8 @@ var daoModelProviderManager *models.ProviderManager
// CodeAuthenticationError without hitting the database.
func TestListMembersAuthCheck(t *testing.T) {
s := &TenantService{}
- _, code, err := s.ListMembers("user-abc", "tenant-xyz")
+ ctx := t.Context()
+ _, code, err := s.ListMembers(ctx, "user-abc", "tenant-xyz")
if err == nil {
t.Fatal("expected error for non-owner, got nil")
}
@@ -48,7 +49,8 @@ func TestListMembersAuthCheck(t *testing.T) {
// TestAddMemberAuthCheck verifies that a non-owner gets CodeAuthenticationError.
func TestAddMemberAuthCheck(t *testing.T) {
s := &TenantService{}
- _, code, err := s.AddMember("user-abc", "tenant-xyz", &AddMemberRequest{Email: "[email protected]"})
+ ctx := t.Context()
+ _, code, err := s.AddMember(ctx, "user-abc", "tenant-xyz", &AddMemberRequest{Email: "[email protected]"})
if err == nil {
t.Fatal("expected error for non-owner, got nil")
}
@@ -61,7 +63,8 @@ func TestAddMemberAuthCheck(t *testing.T) {
func TestAddMemberEmailRequired(t *testing.T) {
// When userID == tenantID (owner) but no email, expect CodeArgumentError.
s := &TenantService{}
- _, code, err := s.AddMember("owner-id", "owner-id", &AddMemberRequest{Email: ""})
+ ctx := t.Context()
+ _, code, err := s.AddMember(ctx, "owner-id", "owner-id", &AddMemberRequest{Email: ""})
if err == nil {
t.Fatal("expected error for empty email, got nil")
}
@@ -73,7 +76,8 @@ func TestAddMemberEmailRequired(t *testing.T) {
// TestRemoveMemberAuthCheck verifies that an unrelated user gets CodeAuthenticationError.
func TestRemoveMemberAuthCheck(t *testing.T) {
s := &TenantService{}
- code, err := s.RemoveMember("user-abc", "tenant-xyz", "user-def")
+ ctx := t.Context()
+ code, err := s.RemoveMember(ctx, "user-abc", "tenant-xyz", "user-def")
if err == nil {
t.Fatal("expected error, got nil")
}
@@ -87,7 +91,8 @@ func TestRemoveMemberAuthCheck(t *testing.T) {
func TestRemoveMemberSelfAllowed(t *testing.T) {
s := &TenantService{}
// userID == targetUserID: auth check should pass.
- code, err := s.RemoveMember("user-abc", "tenant-xyz", "user-abc")
+ ctx := t.Context()
+ code, err := s.RemoveMember(ctx, "user-abc", "tenant-xyz", "user-abc")
if code == common.CodeAuthenticationError {
t.Errorf("self-removal should pass auth check, got CodeAuthenticationError: %v", err)
}
@@ -103,7 +108,8 @@ func TestRemoveMemberSelfAllowed(t *testing.T) {
func TestAcceptInviteAuthCheck(t *testing.T) {
s := &TenantService{}
// nil userTenantDAO: nil guard returns CodeServerError.
- code, err := s.AcceptInvite("user-abc", "tenant-xyz")
+ ctx := t.Context()
+ code, err := s.AcceptInvite(ctx, "user-abc", "tenant-xyz")
if err == nil {
t.Fatal("expected error when userTenantDAO is nil, got nil")
}
diff --git a/internal/service/user.go b/internal/service/user.go
index 01376a30c5..ebe1d27df4 100644
--- a/internal/service/user.go
+++ b/internal/service/user.go
@@ -105,17 +105,17 @@ type UserResponse struct {
func (s *UserService) Register(ctx context.Context, req *RegisterRequest) (*entity.User, common.ErrorCode, error) {
cfg := server.GetConfig()
if !cfg.Authentication.RegisterEnabled {
- return nil, common.CodeOperatingError, fmt.Errorf("User registration is disabled!")
+ return nil, common.CodeOperatingError, fmt.Errorf("user registration is disabled")
}
emailRegex := regexp.MustCompile(`^[\w\._-]+@([\w_-]+\.)+[\w-]{2,}$`)
if !emailRegex.MatchString(req.Email) {
- return nil, common.CodeOperatingError, fmt.Errorf("Invalid email address: %s!", req.Email)
+ return nil, common.CodeOperatingError, fmt.Errorf("invalid email address: %s", req.Email)
}
- existUser, err := s.userDAO.GetByEmail(req.Email)
+ existUser, err := s.userDAO.GetByEmail(ctx, dao.DB, req.Email)
if existUser != nil {
- return nil, common.CodeOperatingError, fmt.Errorf("Email: %s has already registered!", req.Email)
+ return nil, common.CodeOperatingError, fmt.Errorf("email: %s has already registered", req.Email)
}
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, common.CodeServerError, fmt.Errorf("failed to check existing user: %w", err)
@@ -350,9 +350,9 @@ func (s *UserService) getInitTenantLLM(ctx context.Context, userID string) ([]*e
}
// Login user login
-func (s *UserService) Login(req *LoginRequest) (*entity.User, common.ErrorCode, error) {
+func (s *UserService) Login(ctx context.Context, req *LoginRequest) (*entity.User, common.ErrorCode, error) {
// Get user by email (using username field as email)
- user, err := s.userDAO.GetByEmail(req.Username)
+ user, err := s.userDAO.GetByEmail(ctx, dao.DB, req.Username)
if err != nil {
return nil, common.CodeAuthenticationError, fmt.Errorf("invalid email or password")
}
@@ -377,7 +377,7 @@ func (s *UserService) Login(req *LoginRequest) (*entity.User, common.ErrorCode,
user.AccessToken = &token
now := time.Now().Truncate(time.Second)
user.LastLoginTime = &now
- if err := s.userDAO.Update(user); err != nil {
+ if err := s.userDAO.Update(ctx, dao.DB, user); err != nil {
return nil, common.CodeServerError, fmt.Errorf("failed to update user: %w", err)
}
@@ -390,9 +390,9 @@ func (s *UserService) Login(req *LoginRequest) (*entity.User, common.ErrorCode,
// - CodeServerError (500): Password decryption failure
// - CodeForbidden (403): Account disabled
func (s *UserService) LoginByEmail(ctx context.Context, req *EmailLoginRequest) (*entity.User, common.ErrorCode, error) {
- user, err := s.userDAO.GetByEmail(req.Email)
+ user, err := s.userDAO.GetByEmail(ctx, dao.DB, req.Email)
if err != nil {
- return nil, common.CodeAuthenticationError, fmt.Errorf("email: %s is not registered!", req.Email)
+ return nil, common.CodeAuthenticationError, fmt.Errorf("email: %s is not registered", req.Email)
}
decryptedPassword, err := common.DecryptPassword(req.Password)
@@ -401,11 +401,11 @@ func (s *UserService) LoginByEmail(ctx context.Context, req *EmailLoginRequest)
}
if user.Password == nil || !s.VerifyPassword(*user.Password, decryptedPassword) {
- return nil, common.CodeAuthenticationError, fmt.Errorf("email and password do not match!")
+ return nil, common.CodeAuthenticationError, fmt.Errorf("email and password do not match")
}
if user.IsActive == "0" {
- return nil, common.CodeForbidden, fmt.Errorf("This account has been disabled, please contact the administrator!")
+ return nil, common.CodeForbidden, fmt.Errorf("this account has been disabled, please contact the administrator")
}
// Generate new access token
@@ -414,7 +414,7 @@ func (s *UserService) LoginByEmail(ctx context.Context, req *EmailLoginRequest)
now := time.Now().Truncate(time.Second)
user.LastLoginTime = &now
- if err = s.userDAO.Update(user); err != nil {
+ if err = s.userDAO.Update(ctx, dao.DB, user); err != nil {
return nil, common.CodeServerError, fmt.Errorf("failed to update user: %w", err)
}
@@ -423,7 +423,7 @@ func (s *UserService) LoginByEmail(ctx context.Context, req *EmailLoginRequest)
// GetUserByID get user by ID
func (s *UserService) GetUserByID(ctx context.Context, id uint) (*UserResponse, common.ErrorCode, error) {
- user, err := s.userDAO.GetByID(ctx, id)
+ user, err := s.userDAO.GetByID(ctx, dao.DB, id)
if err != nil {
return nil, common.CodeNotFound, err
}
@@ -606,7 +606,7 @@ func (s *UserService) GetUserByToken(ctx context.Context, authorization string)
}
// Get user by access token
- user, err := s.userDAO.GetByAccessToken(accessToken)
+ user, err := s.userDAO.GetByAccessToken(ctx, dao.DB, accessToken)
if err != nil {
return nil, common.CodeUnauthorized, err
}
@@ -615,16 +615,16 @@ func (s *UserService) GetUserByToken(ctx context.Context, authorization string)
}
// UpdateUserAccessToken updates user's access token
-func (s *UserService) UpdateUserAccessToken(user *entity.User, token string) error {
- return s.userDAO.UpdateAccessToken(user, token)
+func (s *UserService) UpdateUserAccessToken(ctx context.Context, user *entity.User, token string) error {
+ return s.userDAO.UpdateAccessToken(ctx, dao.DB, user, token)
}
// Logout invalidates user's access token
-func (s *UserService) Logout(user *entity.User) (common.ErrorCode, error) {
+func (s *UserService) Logout(ctx context.Context, user *entity.User) (common.ErrorCode, error) {
// Invalidate token by setting it to an invalid value
// Similar to Python implementation: "INVALID_" + secrets.token_hex(16)
invalidToken := "INVALID_" + utility.GenerateToken()
- err := s.UpdateUserAccessToken(user, invalidToken)
+ err := s.UpdateUserAccessToken(ctx, user, invalidToken)
if err != nil {
return common.CodeServerError, err
}
@@ -798,7 +798,7 @@ func (s *UserService) UpdateUserSettings(ctx context.Context, user *entity.User,
}
// Save updated user
- if err := s.userDAO.Update(user); err != nil {
+ if err := s.userDAO.Update(ctx, dao.DB, user); err != nil {
return common.CodeServerError, err
}
return common.CodeSuccess, nil
@@ -823,7 +823,7 @@ func (s *UserService) ChangePassword(ctx context.Context, user *entity.User, req
}
// Save updated user
- if err := s.userDAO.Update(user); err != nil {
+ if err := s.userDAO.Update(ctx, dao.DB, user); err != nil {
return common.CodeServerError, err
}
return common.CodeSuccess, nil
@@ -932,7 +932,7 @@ type UserTenantRelation struct {
// GetUserTenantRelationByUserIDWithContext retrieves all user-tenant relationships for a given user ID with context.
func (s *UserTenantService) GetUserTenantRelationByUserIDWithContext(ctx context.Context, userID string) ([]*UserTenantRelation, error) {
- relations, err := s.userTenantDAO.GetByUserIDWithContext(ctx, userID)
+ relations, err := s.userTenantDAO.GetByUserID(ctx, dao.DB, userID)
if err != nil {
return nil, err
}
@@ -990,7 +990,7 @@ func (s *UserService) GetUserByAPIToken(ctx context.Context, authorization strin
}
// Get user by tenant_id from API token
- user, err := s.userDAO.GetByTenantID(userToken.TenantID)
+ user, err := s.userDAO.GetByTenantID(ctx, dao.DB, userToken.TenantID)
if err != nil {
return nil, common.CodeUnauthorized, fmt.Errorf("user not found for this access token")
}
@@ -1071,7 +1071,7 @@ func (s *UserService) GetUserByBetaAPIToken(ctx context.Context, authorization s
}
userToken := userTokens[0]
- user, err := s.userDAO.GetByTenantID(userToken.TenantID)
+ user, err := s.userDAO.GetByTenantID(ctx, dao.DB, userToken.TenantID)
if err != nil {
return nil, common.CodeUnauthorized, fmt.Errorf("user not found for this beta access token")
}
@@ -1094,11 +1094,11 @@ func (s *UserService) GetUserByBetaAPIToken(ctx context.Context, authorization s
// code itself is never sent to the client outside the rendered image.
//
// Refuses unknown emails to avoid leaking the user list — matches Python.
-func (s *UserService) ForgotIssueCaptcha(email string) (captchaID, imageDataURL string, code common.ErrorCode, err error) {
+func (s *UserService) ForgotIssueCaptcha(ctx context.Context, email string) (captchaID, imageDataURL string, code common.ErrorCode, err error) {
if email == "" {
return "", "", common.CodeArgumentError, fmt.Errorf("email is required")
}
- if _, err := s.userDAO.GetByEmail(email); err != nil {
+ if _, err = s.userDAO.GetByEmail(ctx, dao.DB, email); err != nil {
return "", "", common.CodeDataError, fmt.Errorf("invalid email")
}
@@ -1119,11 +1119,11 @@ func (s *UserService) ForgotIssueCaptcha(email string) (captchaID, imageDataURL
// stored in Redis under the keys returned by utility.OTPRedisKeys.
// Resend cooldown and per-email lockout behaviour otherwise match the
// Python implementation byte-for-byte.
-func (s *UserService) ForgotSendOTP(email, captchaID, captcha string) (common.ErrorCode, error) {
+func (s *UserService) ForgotSendOTP(ctx context.Context, email, captchaID, captcha string) (common.ErrorCode, error) {
if email == "" || captchaID == "" || captcha == "" {
return common.CodeArgumentError, fmt.Errorf("email, captcha_id and captcha required")
}
- if _, err := s.userDAO.GetByEmail(email); err != nil {
+ if _, err := s.userDAO.GetByEmail(ctx, dao.DB, email); err != nil {
return common.CodeDataError, fmt.Errorf("invalid email")
}
@@ -1215,14 +1215,14 @@ func (s *UserService) ForgotSendOTP(email, captchaID, captcha string) (common.Er
return common.CodeSuccess, nil
}
-// ForgotVerifyOTP checks an OTP submitted by the user. On success it
+// ForgotVerifyOTP checks an OTP submitted by the user. On success, it
// consumes the OTP/attempt counters and writes a short-lived "verified"
// flag the reset endpoint will gate on.
-func (s *UserService) ForgotVerifyOTP(email, otp string) (common.ErrorCode, error) {
+func (s *UserService) ForgotVerifyOTP(ctx context.Context, email, otp string) (common.ErrorCode, error) {
if email == "" || otp == "" {
return common.CodeArgumentError, fmt.Errorf("email and otp are required")
}
- if _, err := s.userDAO.GetByEmail(email); err != nil {
+ if _, err := s.userDAO.GetByEmail(ctx, dao.DB, email); err != nil {
return common.CodeDataError, fmt.Errorf("invalid email")
}
@@ -1291,7 +1291,7 @@ type ForgotResetPasswordRequest struct {
// updates the password hash, and clears the verified flag. Returns the
// user so the handler can auto-login (matching Python's
// `construct_response(auth=user.get_id())`).
-func (s *UserService) ForgotResetPassword(req *ForgotResetPasswordRequest) (*entity.User, common.ErrorCode, error) {
+func (s *UserService) ForgotResetPassword(ctx context.Context, req *ForgotResetPasswordRequest) (*entity.User, common.ErrorCode, error) {
if req.Email == "" || req.NewPassword == "" || req.ConfirmNewPassword == "" {
return nil, common.CodeArgumentError, fmt.Errorf("email and passwords are required")
}
@@ -1314,7 +1314,7 @@ func (s *UserService) ForgotResetPassword(req *ForgotResetPasswordRequest) (*ent
return nil, common.CodeArgumentError, fmt.Errorf("passwords do not match")
}
- user, err := s.userDAO.GetByEmail(req.Email)
+ user, err := s.userDAO.GetByEmail(ctx, dao.DB, req.Email)
if err != nil {
return nil, common.CodeDataError, fmt.Errorf("invalid email")
}
@@ -1332,7 +1332,7 @@ func (s *UserService) ForgotResetPassword(req *ForgotResetPasswordRequest) (*ent
now := time.Now().Truncate(time.Second)
user.LastLoginTime = &now
- if err := s.userDAO.Update(user); err != nil {
+ if err = s.userDAO.Update(ctx, dao.DB, user); err != nil {
return nil, common.CodeServerError, fmt.Errorf("failed to reset password: %w", err)
}
diff --git a/test/testcases/restful_api/test_chats.py b/test/testcases/restful_api/test_chats.py
index 4b90675489..e4b5d2a65d 100644
--- a/test/testcases/restful_api/test_chats.py
+++ b/test/testcases/restful_api/test_chats.py
@@ -322,7 +322,7 @@ def test_chat_list_default_get_and_separate_lookup_contract(rest_client, clear_c
assert invalid_get_res.status_code == 200
invalid_get_payload = invalid_get_res.json()
assert invalid_get_payload["code"] == 109, invalid_get_payload
- assert invalid_get_payload["message"] == "No authorization.", invalid_get_payload
+ assert invalid_get_payload["message"] == "no authorization", invalid_get_payload
for chat_id, keywords, expected_count in ((ids[0], "list_default_0", 1), (ids[0], "list_default_1", 1), (ids[0], "unknown", 0)):
get_res = rest_client.get(f"/chats/{chat_id}")
@@ -852,7 +852,7 @@ def test_chat_session_create_and_update_guard_matrix_unit(monkeypatch):
_set_route_unit_request_json(monkeypatch, module, {"name": "session"})
monkeypatch.setattr(module.DialogService, "query", lambda **_kwargs: [])
res = _run(module.create_session.__wrapped__("chat-1"))
- assert res["message"] == "No authorization."
+ assert res["message"] == "no authorization"
dia = SimpleNamespace(prompt_config={"prologue": "hello"})
monkeypatch.setattr(module.DialogService, "query", lambda **_kwargs: [dia])
@@ -870,20 +870,20 @@ def test_chat_session_create_and_update_guard_matrix_unit(monkeypatch):
monkeypatch.setattr(module.ConversationService, "query", lambda **_kwargs: [SimpleNamespace(id="session-1")])
monkeypatch.setattr(module.DialogService, "query", lambda **_kwargs: [])
res = _run(module.update_session.__wrapped__("chat-1", "session-1"))
- assert res["message"] == "No authorization."
+ assert res["message"] == "no authorization"
monkeypatch.setattr(module.DialogService, "query", lambda **_kwargs: [SimpleNamespace(id="chat-1")])
_set_route_unit_request_json(monkeypatch, module, {"message": []})
res = _run(module.update_session.__wrapped__("chat-1", "session-1"))
- assert "`messages` cannot be changed." in res["message"]
+ assert "`messages` cannot be changed" in res["message"]
_set_route_unit_request_json(monkeypatch, module, {"reference": []})
res = _run(module.update_session.__wrapped__("chat-1", "session-1"))
- assert "`reference` cannot be changed." in res["message"]
+ assert "`reference` cannot be changed" in res["message"]
_set_route_unit_request_json(monkeypatch, module, {"name": ""})
res = _run(module.update_session.__wrapped__("chat-1", "session-1"))
- assert "`name` can not be empty." in res["message"]
+ assert "`name` can not be empty" in res["message"]
_set_route_unit_request_json(monkeypatch, module, {"name": "renamed"})
monkeypatch.setattr(module.ConversationService, "update_by_id", lambda *_args, **_kwargs: False)
@@ -1953,7 +1953,7 @@ def test_chat_update_mapping_and_validation_branches_p2(rest_client, clear_chats
assert unauthorized.status_code == 200
unauthorized_payload = unauthorized.json()
assert unauthorized_payload["code"] == 109, unauthorized_payload
- assert unauthorized_payload["message"] == "No authorization.", unauthorized_payload
+ assert unauthorized_payload["message"] == "no authorization", unauthorized_payload
quote_res = rest_client.patch(f"/chats/{chat_id}", json={"prompt_config": {"quote": False}})
assert quote_res.status_code == 200
diff --git a/test/testcases/restful_api/test_connector_routes_unit.py b/test/testcases/restful_api/test_connector_routes_unit.py
index 53df4c8219..4797e66cdd 100644
--- a/test/testcases/restful_api/test_connector_routes_unit.py
+++ b/test/testcases/restful_api/test_connector_routes_unit.py
@@ -451,7 +451,7 @@ def test_connector_by_id_routes_reject_cross_tenant_access(monkeypatch):
]
assert all(res["code"] == module.RetCode.AUTHENTICATION_ERROR for res in responses)
- assert all(res["message"] == "No authorization." for res in responses)
+ assert all(res["message"] == "no authorization" for res in responses)
assert all(res["data"] is False for res in responses)
assert touched == []
diff --git a/test/testcases/restful_api/test_datasets.py b/test/testcases/restful_api/test_datasets.py
index a97338a76b..8609daea22 100644
--- a/test/testcases/restful_api/test_datasets.py
+++ b/test/testcases/restful_api/test_datasets.py
@@ -436,13 +436,13 @@ def test_dataset_update_embedding_model_contract(rest_client, clear_datasets, em
@pytest.mark.parametrize(
"name, embedding_model, expected_fragment",
[
- ("empty", "", "Embedding model identifier must follow <model_name>@<provider> format"),
- ("space", " ", "Embedding model identifier must follow <model_name>@<provider> format"),
- ("missing_at", "BAAI/bge-small-en-v1.5Builtin", "Embedding model identifier must follow <model_name>@<provider> format"),
- ("missing_model_name", "@Builtin", "Both model_name and provider must be non-empty strings"),
- ("missing_provider", "BAAI/bge-small-en-v1.5@", "Both model_name and provider must be non-empty strings"),
- ("whitespace_only_model_name", " @Builtin", "Both model_name and provider must be non-empty strings"),
- ("whitespace_only_provider", "BAAI/bge-small-en-v1.5@ ", "Both model_name and provider must be non-empty strings"),
+ ("empty", "", "embedding model identifier must follow <model_name>@<provider> format"),
+ ("space", " ", "embedding model identifier must follow <model_name>@<provider> format"),
+ ("missing_at", "BAAI/bge-small-en-v1.5Builtin", "embedding model identifier must follow <model_name>@<provider> format"),
+ ("missing_model_name", "@Builtin", "both model_name and provider must be non-empty strings"),
+ ("missing_provider", "BAAI/bge-small-en-v1.5@", "both model_name and provider must be non-empty strings"),
+ ("whitespace_only_model_name", " @Builtin", "both model_name and provider must be non-empty strings"),
+ ("whitespace_only_provider", "BAAI/bge-small-en-v1.5@ ", "both model_name and provider must be non-empty strings"),
],
ids=["empty", "space", "missing_at", "empty_model_name", "empty_provider", "whitespace_only_model_name", "whitespace_only_provider"],
)
@@ -728,9 +728,9 @@ def test_dataset_update_avatar_invalid_and_none_contract(rest_client, clear_data
image_path = create_image_file(tmp_path / "dataset_update_avatar_invalid.png")
encoded_avatar = encode_avatar(image_path)
invalid_prefix_cases = [
- ("", "Missing MIME prefix. Expected format: data:<mime>;base64,<data>"),
- ("data:image/png;base64", "Missing MIME prefix. Expected format: data:<mime>;base64,<data>"),
- ("invalid_mine_prefix:image/png;base64,", "Invalid MIME prefix format. Must start with 'data:'"),
+ ("", "missing MIME prefix. Expected format: data:<mime>;base64,<data>"),
+ ("data:image/png;base64", "missing MIME prefix. Expected format: data:<mime>;base64,<data>"),
+ ("invalid_mine_prefix:image/png;base64,", "invalid MIME prefix format. Must start with 'data:'"),
("data:unsupported_mine_type;base64,", "Unsupported MIME type. Allowed: ['image/jpeg', 'image/png']"),
]
for prefix, expected_message in invalid_prefix_cases:
@@ -742,7 +742,7 @@ def test_dataset_update_avatar_invalid_and_none_contract(rest_client, clear_data
payload = res.json()
assert payload["code"] == ARGUMENT_ERROR_CODE, payload
if IS_GO_PROXY and expected_message.startswith("Unsupported MIME type"):
- expected_message = "Unsupported MIME type. Allowed: [image/jpeg image/png]"
+ expected_message = "unsupported MIME type. Allowed: [image/jpeg image/png]"
assert expected_message in payload["message"], payload
none_res = rest_client.put(f"/datasets/{dataset_id}", json={"avatar": None})
@@ -916,7 +916,7 @@ def test_dataset_update_chunk_method_invalid_contract(rest_client, clear_dataset
elif IS_GO_PROXY and chunk_method == "":
assert payload["message"] == "parser_id is required when parse_type is BuiltIn", payload
elif IS_GO_PROXY:
- assert payload["message"].startswith("Input should be 'audio', 'book'") and payload["message"].endswith("or 'table'"), payload
+ assert payload["message"].startswith("input should be 'audio', 'book'") and payload["message"].endswith("or 'table'"), payload
else:
assert expected_chunk_message in payload["message"], payload
@@ -926,7 +926,7 @@ def test_dataset_update_chunk_method_invalid_contract(rest_client, clear_dataset
_skip_go_ignored_null(none_payload, PARSER_ID_FIELD)
assert none_payload["code"] == ARGUMENT_ERROR_CODE, none_payload
if IS_GO_PROXY:
- assert none_payload["message"].startswith("Input should be 'audio', 'book'") and none_payload["message"].endswith("or 'table'"), none_payload
+ assert none_payload["message"].startswith("input should be 'audio', 'book'") and none_payload["message"].endswith("or 'table'"), none_payload
else:
assert expected_chunk_message in none_payload["message"], none_payload
@@ -1131,7 +1131,7 @@ def test_dataset_create_name_validation(rest_client, clear_datasets, name, expec
if not name:
expected_fragment = "failed on the 'required' tag"
elif not name.strip():
- expected_fragment = "Dataset name can't be empty."
+ expected_fragment = "dataset name can't be empty"
else:
expected_fragment = f"Dataset name length is {len(name)} which is large than {DATASET_NAME_LIMIT}"
assert expected_fragment in payload["message"], payload
@@ -1272,13 +1272,13 @@ def test_dataset_create_embedding_model_contract(rest_client, clear_datasets, na
@pytest.mark.parametrize(
"name, embedding_model, expected_fragment",
[
- ("empty", "", "Embedding model identifier must follow <model_name>@<provider> format"),
- ("space", " ", "Embedding model identifier must follow <model_name>@<provider> format"),
- ("missing_at", "BAAI/bge-small-en-v1.5Builtin", "Embedding model identifier must follow <model_name>@<provider> format"),
- ("missing_model_name", "@Builtin", "Both model_name and provider must be non-empty strings"),
- ("missing_provider", "BAAI/bge-small-en-v1.5@", "Both model_name and provider must be non-empty strings"),
- ("whitespace_only_model_name", " @Builtin", "Both model_name and provider must be non-empty strings"),
- ("whitespace_only_provider", "BAAI/bge-small-env1.5@ ", "Both model_name and provider must be non-empty strings"),
+ ("empty", "", "embedding model identifier must follow <model_name>@<provider> format"),
+ ("space", " ", "embedding model identifier must follow <model_name>@<provider> format"),
+ ("missing_at", "BAAI/bge-small-en-v1.5Builtin", "embedding model identifier must follow <model_name>@<provider> format"),
+ ("missing_model_name", "@Builtin", "both model_name and provider must be non-empty strings"),
+ ("missing_provider", "BAAI/bge-small-en-v1.5@", "both model_name and provider must be non-empty strings"),
+ ("whitespace_only_model_name", " @Builtin", "both model_name and provider must be non-empty strings"),
+ ("whitespace_only_provider", "BAAI/bge-small-env1.5@ ", "both model_name and provider must be non-empty strings"),
],
ids=["empty", "space", "missing_at", "empty_model_name", "empty_provider", "whitespace_only_model_name", "whitespace_only_provider"],
)
@@ -1587,9 +1587,9 @@ def test_dataset_create_avatar_contract(rest_client, clear_datasets, tmp_path):
image_path = create_image_file(tmp_path / "ragflow_test.png")
encoded_avatar = encode_avatar(image_path)
invalid_prefix_cases = [
- ("empty_prefix", "", "Missing MIME prefix. Expected format: data:<mime>;base64,<data>"),
- ("missing_comma", "data:image/png;base64", "Missing MIME prefix. Expected format: data:<mime>;base64,<data>"),
- ("unsupported_mine_type", "invalid_mine_prefix:image/png;base64,", "Invalid MIME prefix format. Must start with 'data:'"),
+ ("empty_prefix", "", "missing MIME prefix. Expected format: data:<mime>;base64,<data>"),
+ ("missing_comma", "data:image/png;base64", "missing MIME prefix. Expected format: data:<mime>;base64,<data>"),
+ ("unsupported_mine_type", "invalid_mine_prefix:image/png;base64,", "invalid MIME prefix format. Must start with 'data:'"),
("invalid_mine_type", "data:unsupported_mine_type;base64,", "Unsupported MIME type. Allowed: ['image/jpeg', 'image/png']"),
]
for name, prefix, expected_message in invalid_prefix_cases:
@@ -1601,7 +1601,7 @@ def test_dataset_create_avatar_contract(rest_client, clear_datasets, tmp_path):
payload = res.json()
assert payload["code"] == ARGUMENT_ERROR_CODE, payload
if IS_GO_PROXY and expected_message.startswith("Unsupported MIME type"):
- expected_message = "Unsupported MIME type. Allowed: [image/jpeg image/png]"
+ expected_message = "unsupported MIME type. Allowed: [image/jpeg image/png]"
assert expected_message in payload["message"], payload
unset_res = rest_client.post("/datasets", json={"name": "avatar_unset"})
@@ -1693,7 +1693,7 @@ def test_dataset_create_permission_and_chunk_method_contract(rest_client, clear_
elif IS_GO_PROXY and chunk_method == "":
assert payload["message"] == "parser_id is required when parse_type is BuiltIn", payload
elif IS_GO_PROXY:
- assert payload["message"].startswith("Input should be 'audio', 'book'") and payload["message"].endswith("or 'table'"), payload
+ assert payload["message"].startswith("input should be 'audio', 'book'") and payload["message"].endswith("or 'table'"), payload
else:
assert expected_chunk_message in payload["message"], payload
diff --git a/test/testcases/restful_api/test_documents.py b/test/testcases/restful_api/test_documents.py
index 1edad952b8..24d064d779 100644
--- a/test/testcases/restful_api/test_documents.py
+++ b/test/testcases/restful_api/test_documents.py
@@ -584,7 +584,7 @@ def test_documents_update_invalid_dataset_and_document_contract(rest_client, cre
assert invalid_dataset_res.status_code == 200
invalid_dataset_body = invalid_dataset_res.json()
assert invalid_dataset_body["code"] == 102, invalid_dataset_body
- assert "You don't own the dataset." in invalid_dataset_body["message"], invalid_dataset_body
+ assert "you don't own the dataset" in invalid_dataset_body["message"], invalid_dataset_body
invalid_document_res = rest_client.patch(
f"/datasets/{dataset_id}/documents/{INVALID_ID_32}",
@@ -593,7 +593,7 @@ def test_documents_update_invalid_dataset_and_document_contract(rest_client, cre
assert invalid_document_res.status_code == 200
invalid_document_body = invalid_document_res.json()
assert invalid_document_body["code"] == 102, invalid_document_body
- assert invalid_document_body["message"] == "The dataset doesn't own the document.", invalid_document_body
+ assert invalid_document_body["message"] == "the dataset doesn't own the document", invalid_document_body
@pytest.mark.p2
@@ -681,7 +681,7 @@ def test_documents_update_meta_fields_contract(rest_client, create_dataset, tmp_
assert invalid_meta_doc_res.status_code == 200
invalid_meta_doc_body = invalid_meta_doc_res.json()
assert invalid_meta_doc_body["code"] == 102, invalid_meta_doc_body
- assert "The dataset doesn't own the document." in invalid_meta_doc_body["message"], invalid_meta_doc_body
+ assert "the dataset doesn't own the document" in invalid_meta_doc_body["message"], invalid_meta_doc_body
@pytest.mark.p2
@@ -1012,7 +1012,7 @@ def test_document_metadata_config_contract(rest_client, create_document):
assert invalid_dataset_res.status_code == 200
invalid_dataset_payload = invalid_dataset_res.json()
assert invalid_dataset_payload["code"] == 102, invalid_dataset_payload
- assert invalid_dataset_payload["message"] == "You don't own the dataset.", invalid_dataset_payload
+ assert invalid_dataset_payload["message"] == "you don't own the dataset", invalid_dataset_payload
invalid_document_res = rest_client.put(
f"/datasets/{dataset_id}/documents/{INVALID_ID_32}/metadata/config",
@@ -1021,7 +1021,7 @@ def test_document_metadata_config_contract(rest_client, create_document):
assert invalid_document_res.status_code == 200
invalid_document_payload = invalid_document_res.json()
assert invalid_document_payload["code"] == 102, invalid_document_payload
- assert invalid_document_payload["message"] == f"Document {INVALID_ID_32} not found in dataset {dataset_id}", invalid_document_payload
+ assert invalid_document_payload["message"] == f"document {INVALID_ID_32} not found in dataset {dataset_id}", invalid_document_payload
update_payload = {"metadata": {"author": "alice", "tags": ["one", "two"]}}
update_res = rest_client.put(
diff --git a/test/testcases/restful_api/test_file_routes_unit.py b/test/testcases/restful_api/test_file_routes_unit.py
index 339d737c8d..83e9c04d3d 100644
--- a/test/testcases/restful_api/test_file_routes_unit.py
+++ b/test/testcases/restful_api/test_file_routes_unit.py
@@ -619,14 +619,14 @@ def test_convert_branch_matrix_unit(monkeypatch):
monkeypatch.setattr(module, "check_file_team_permission", lambda *_args, **_kwargs: False)
res = _run(module.convert())
assert res["code"] == 102
- assert res["message"] == "No authorization."
+ assert res["message"] == "no authorization"
# Unauthorized dataset access is rejected before scheduling background work.
monkeypatch.setattr(module, "check_file_team_permission", lambda *_args, **_kwargs: True)
monkeypatch.setattr(module, "check_kb_team_permission", lambda *_args, **_kwargs: False)
res = _run(module.convert())
assert res["code"] == 102
- assert res["message"] == "No authorization."
+ assert res["message"] == "no authorization"
# Valid file and kb schedule background work and return data=True immediately.
monkeypatch.setattr(module, "check_kb_team_permission", lambda *_args, **_kwargs: True)
@@ -993,7 +993,7 @@ def test_get_file_content_checks_permission(monkeypatch):
ok, message = module.get_file_content("tenant1", "file1")
assert ok is False
- assert message == "No authorization."
+ assert message == "no authorization"
monkeypatch.setattr(module, "check_file_team_permission", lambda *_args, **_kwargs: True)
ok, file = module.get_file_content("tenant1", "file1")
diff --git a/test/testcases/restful_api/test_searches.py b/test/testcases/restful_api/test_searches.py
index 2c8bab49b0..ccd3be2ac2 100644
--- a/test/testcases/restful_api/test_searches.py
+++ b/test/testcases/restful_api/test_searches.py
@@ -14,7 +14,6 @@
# limitations under the License.
#
-import json
import uuid
import pytest
@@ -102,7 +101,7 @@ def test_search_update_invalid_search_id(rest_client):
assert res.status_code == 200
payload = res.json()
assert payload["code"] == 109, payload
- assert "No authorization" in payload["message"], payload
+ assert "no authorization" in payload["message"], payload
@pytest.mark.p2
@@ -151,4 +150,3 @@ def test_search_completion_sse_shape_when_kb_ids_provided(rest_client, search_re
payload = res.json()
assert payload["code"] == 102, payload
assert "You don't own the dataset nonexistent_dataset" in payload["message"], payload
-
diff --git a/test/testcases/restful_api/test_sessions.py b/test/testcases/restful_api/test_sessions.py
index 1c69131d42..328f47fe2c 100644
--- a/test/testcases/restful_api/test_sessions.py
+++ b/test/testcases/restful_api/test_sessions.py
@@ -98,7 +98,7 @@ def test_session_create_name_validation(rest_client, create_chat):
assert res.status_code == 200
payload = res.json()
assert payload["code"] == 102, payload
- assert "`name` can not be empty." in payload["message"], payload
+ assert "`name` can not be empty" in payload["message"], payload
@pytest.mark.p2
@@ -114,13 +114,13 @@ def test_session_update_blocks_messages_and_reference(rest_client, create_chat):
assert msg_res.status_code == 200
msg_payload = msg_res.json()
assert msg_payload["code"] == 102, msg_payload
- assert "`messages` cannot be changed." in msg_payload["message"], msg_payload
+ assert "`messages` cannot be changed" in msg_payload["message"], msg_payload
ref_res = rest_client.patch(f"/chats/{chat_id}/sessions/{session_id}", json={"reference": []})
assert ref_res.status_code == 200
ref_payload = ref_res.json()
assert ref_payload["code"] == 102, ref_payload
- assert "`reference` cannot be changed." in ref_payload["message"], ref_payload
+ assert "`reference` cannot be changed" in ref_payload["message"], ref_payload
@pytest.mark.p1
@@ -146,7 +146,7 @@ def test_session_create_validation_and_deleted_chat_contract(rest_client, create
assert invalid_chat_res.status_code == 200
invalid_chat_payload = invalid_chat_res.json()
assert invalid_chat_payload["code"] == 109, invalid_chat_payload
- assert invalid_chat_payload["message"] == "No authorization.", invalid_chat_payload
+ assert invalid_chat_payload["message"] == "no authorization", invalid_chat_payload
for scenario_name, payload in (
("valid", {"name": "valid_name"}),
@@ -163,7 +163,7 @@ def test_session_create_validation_and_deleted_chat_contract(rest_client, create
assert body["data"]["chat_id"] == chat_id, (scenario_name, body)
else:
assert body["code"] == 102, (scenario_name, body)
- assert body["message"] == "`name` can not be empty.", (scenario_name, body)
+ assert body["message"] == "`name` can not be empty", (scenario_name, body)
duplicate_first = rest_client.post(f"/chats/{chat_id}/sessions", json={"name": "duplicated_name"}).json()
duplicate_second = rest_client.post(f"/chats/{chat_id}/sessions", json={"name": "duplicated_name"}).json()
@@ -194,7 +194,7 @@ def test_session_create_validation_and_deleted_chat_contract(rest_client, create
assert create_after_delete.status_code == 200
create_after_delete_payload = create_after_delete.json()
assert create_after_delete_payload["code"] == 109, create_after_delete_payload
- assert create_after_delete_payload["message"] == "No authorization.", create_after_delete_payload
+ assert create_after_delete_payload["message"] == "no authorization", create_after_delete_payload
@pytest.mark.p2
@@ -234,7 +234,7 @@ def test_session_delete_requires_auth_and_invalid_target_contract(rest_client, c
assert invalid_chat_res.status_code == 200
invalid_chat_payload = invalid_chat_res.json()
assert invalid_chat_payload["code"] == 109, invalid_chat_payload
- assert invalid_chat_payload["message"] == "No authorization.", invalid_chat_payload
+ assert invalid_chat_payload["message"] == "no authorization", invalid_chat_payload
@pytest.mark.p2
@@ -394,7 +394,7 @@ def test_session_list_filter_and_deleted_chat_contract(rest_client, create_chat)
assert invalid_chat_res.status_code == 200
invalid_chat_payload = invalid_chat_res.json()
assert invalid_chat_payload["code"] == 109, invalid_chat_payload
- assert invalid_chat_payload["message"] == "No authorization.", invalid_chat_payload
+ assert invalid_chat_payload["message"] == "no authorization", invalid_chat_payload
delete_chat_res = rest_client.delete("/chats", json={"ids": [chat_id]})
assert delete_chat_res.status_code == 200
@@ -405,7 +405,7 @@ def test_session_list_filter_and_deleted_chat_contract(rest_client, create_chat)
assert deleted_list_res.status_code == 200
deleted_list_payload = deleted_list_res.json()
assert deleted_list_payload["code"] == 109, deleted_list_payload
- assert deleted_list_payload["message"] == "No authorization.", deleted_list_payload
+ assert deleted_list_payload["message"] == "no authorization", deleted_list_payload
@pytest.mark.p2
@@ -498,7 +498,7 @@ def test_session_update_requires_auth_and_invalid_target_contract(rest_client, c
assert invalid_chat_res.status_code == 200
invalid_chat_payload = invalid_chat_res.json()
assert invalid_chat_payload["code"] == 109, invalid_chat_payload
- assert invalid_chat_payload["message"] == "No authorization.", invalid_chat_payload
+ assert invalid_chat_payload["message"] == "no authorization", invalid_chat_payload
empty_session_res = rest_client.patch(f"/chats/{chat_id}/sessions/", json={"name": "x"})
assert empty_session_res.status_code == 200
@@ -520,8 +520,8 @@ def test_session_update_name_and_param_contract(rest_client, create_chat):
for scenario_name, payload, expected_code, expected_name_or_message in (
("valid", {"name": "valid_name"}, 0, "valid_name"),
- ("empty", {"name": ""}, 102, "`name` can not be empty."),
- ("numeric", {"name": 1}, 102, "`name` can not be empty."),
+ ("empty", {"name": ""}, 102, "`name` can not be empty"),
+ ("numeric", {"name": 1}, 102, "`name` can not be empty"),
("duplicate", {"name": "duplicated_name"}, 0, "duplicated_name"),
("case insensitive upper", {"name": "CASE INSENSITIVE UPDATE"}, 0, "CASE INSENSITIVE UPDATE"),
("case insensitive lower", {"name": "case insensitive update"}, 0, "case insensitive update"),
@@ -552,7 +552,7 @@ def test_session_update_name_and_param_contract(rest_client, create_chat):
assert update_after_delete_res.status_code == 200
update_after_delete_payload = update_after_delete_res.json()
assert update_after_delete_payload["code"] == 109, update_after_delete_payload
- assert update_after_delete_payload["message"] == "No authorization.", update_after_delete_payload
+ assert update_after_delete_payload["message"] == "no authorization", update_after_delete_payload
@pytest.mark.p2
@@ -759,4 +759,4 @@ def test_chat_completion_validation_errors(rest_client, create_chat):
assert invalid_chat.status_code == 200
invalid_chat_payload = invalid_chat.json()
assert invalid_chat_payload["code"] == 109, invalid_chat_payload
- assert "No authorization." in invalid_chat_payload["message"], invalid_chat_payload
+ assert "no authorization" in invalid_chat_payload["message"], invalid_chat_payload
diff --git a/test/testcases/restful_api/test_user_tenant_routes_unit.py b/test/testcases/restful_api/test_user_tenant_routes_unit.py
index 1076acd4ac..9047d781ac 100644
--- a/test/testcases/restful_api/test_user_tenant_routes_unit.py
+++ b/test/testcases/restful_api/test_user_tenant_routes_unit.py
@@ -208,7 +208,7 @@ def test_user_list_auth_success_exception_matrix_unit(monkeypatch):
module.current_user.id = "other-user"
res = module.user_list("tenant-1")
assert res["code"] == module.RetCode.AUTHENTICATION_ERROR, res
- assert res["message"] == "No authorization.", res
+ assert res["message"] == "no authorization", res
module.current_user.id = "tenant-1"
monkeypatch.setattr(
@@ -235,7 +235,7 @@ def test_create_invite_role_and_email_failure_matrix_unit(monkeypatch):
_set_request_json(monkeypatch, module, {"email": "[email protected]"})
res = _run(module.create("tenant-1"))
assert res["code"] == module.RetCode.AUTHENTICATION_ERROR, res
- assert res["message"] == "No authorization.", res
+ assert res["message"] == "no authorization", res
module.current_user.id = "tenant-1"
monkeypatch.setattr(module.UserService, "query", lambda **_kwargs: [])
@@ -283,7 +283,7 @@ def test_rm_and_tenant_list_matrix_unit(monkeypatch):
_set_request_json(monkeypatch, module, {"user_id": "user-2"})
res = _run(module.rm("tenant-1"))
assert res["code"] == module.RetCode.AUTHENTICATION_ERROR, res
- assert res["message"] == "No authorization.", res
+ assert res["message"] == "no authorization", res
module.current_user.id = "tenant-1"
deleted = []
diff --git a/test/testcases/test_http_api/test_chat_assistant_management/test_chat_sdk_routes_unit.py b/test/testcases/test_http_api/test_chat_assistant_management/test_chat_sdk_routes_unit.py
index b07f5f2317..639e2abcea 100644
--- a/test/testcases/test_http_api/test_chat_assistant_management/test_chat_sdk_routes_unit.py
+++ b/test/testcases/test_http_api/test_chat_assistant_management/test_chat_sdk_routes_unit.py
@@ -892,7 +892,7 @@ def test_chat_session_create_and_update_guard_matrix_unit(monkeypatch):
_set_request_json(monkeypatch, module, {"name": "session"})
monkeypatch.setattr(module.DialogService, "query", lambda **_kwargs: [])
res = _run(module.create_session.__wrapped__("chat-1"))
- assert res["message"] == "No authorization."
+ assert res["message"] == "no authorization"
dia = SimpleNamespace(prompt_config={"prologue": "hello"})
monkeypatch.setattr(module.DialogService, "query", lambda **_kwargs: [dia])
@@ -910,20 +910,20 @@ def test_chat_session_create_and_update_guard_matrix_unit(monkeypatch):
monkeypatch.setattr(module.ConversationService, "query", lambda **_kwargs: [SimpleNamespace(id="session-1")])
monkeypatch.setattr(module.DialogService, "query", lambda **_kwargs: [])
res = _run(module.update_session.__wrapped__("chat-1", "session-1"))
- assert res["message"] == "No authorization."
+ assert res["message"] == "no authorization"
monkeypatch.setattr(module.DialogService, "query", lambda **_kwargs: [SimpleNamespace(id="chat-1")])
_set_request_json(monkeypatch, module, {"message": []})
res = _run(module.update_session.__wrapped__("chat-1", "session-1"))
- assert "`messages` cannot be changed." in res["message"]
+ assert "`messages` cannot be changed" in res["message"]
_set_request_json(monkeypatch, module, {"reference": []})
res = _run(module.update_session.__wrapped__("chat-1", "session-1"))
- assert "`reference` cannot be changed." in res["message"]
+ assert "`reference` cannot be changed" in res["message"]
_set_request_json(monkeypatch, module, {"name": ""})
res = _run(module.update_session.__wrapped__("chat-1", "session-1"))
- assert "`name` can not be empty." in res["message"]
+ assert "`name` can not be empty" in res["message"]
_set_request_json(monkeypatch, module, {"name": "renamed"})
monkeypatch.setattr(module.ConversationService, "update_by_id", lambda *_args, **_kwargs: False)
diff --git a/test/testcases/test_http_api/test_chat_assistant_management/test_list_chat_assistants.py b/test/testcases/test_http_api/test_chat_assistant_management/test_list_chat_assistants.py
index 85c9aa78de..08b41e810f 100644
--- a/test/testcases/test_http_api/test_chat_assistant_management/test_list_chat_assistants.py
+++ b/test/testcases/test_http_api/test_chat_assistant_management/test_list_chat_assistants.py
@@ -227,7 +227,7 @@ class TestChatAssistantsList:
"chat_assistant_id, expected_code, expected_message",
[
(lambda r: r[0], 0, ""),
- ("unknown", 109, "No authorization."),
+ ("unknown", 109, "no authorization"),
],
)
def test_get_chat_assistant(
diff --git a/test/testcases/test_http_api/test_chat_assistant_management/test_update_chat_assistant.py b/test/testcases/test_http_api/test_chat_assistant_management/test_update_chat_assistant.py
index 0c4b243fe9..a6f69191fd 100644
--- a/test/testcases/test_http_api/test_chat_assistant_management/test_update_chat_assistant.py
+++ b/test/testcases/test_http_api/test_chat_assistant_management/test_update_chat_assistant.py
@@ -231,10 +231,10 @@ class TestChatAssistantUpdate:
dataset_id, _, chat_assistant_ids = add_chat_assistants_func
chat_id = chat_assistant_ids[0]
- # Auth: non-owned chat returns 109 "No authorization."
+ # Auth: non-owned chat returns 109 "no authorization"
res = patch_chat_assistant(HttpApiAuth, "invalid-chat-id", {"name": "anything"})
assert res["code"] == 109
- assert res["message"] == "No authorization."
+ assert res["message"] == "no authorization"
# PATCH: toggle quote via prompt_config
res = patch_chat_assistant(HttpApiAuth, chat_id, {"prompt_config": {"quote": False}})
diff --git a/test/testcases/test_http_api/test_dataset_management/test_create_dataset.py b/test/testcases/test_http_api/test_dataset_management/test_create_dataset.py
index 46b6e8891c..e56910009f 100644
--- a/test/testcases/test_http_api/test_dataset_management/test_create_dataset.py
+++ b/test/testcases/test_http_api/test_dataset_management/test_create_dataset.py
@@ -163,9 +163,9 @@ class TestDatasetCreate:
@pytest.mark.parametrize(
"name, prefix, expected_message",
[
- ("empty_prefix", "", "Missing MIME prefix. Expected format: data:<mime>;base64,<data>"),
- ("missing_comma", "data:image/png;base64", "Missing MIME prefix. Expected format: data:<mime>;base64,<data>"),
- ("unsupported_mine_type", "invalid_mine_prefix:image/png;base64,", "Invalid MIME prefix format. Must start with 'data:'"),
+ ("empty_prefix", "", "missing MIME prefix. Expected format: data:<mime>;base64,<data>"),
+ ("missing_comma", "data:image/png;base64", "missing MIME prefix. Expected format: data:<mime>;base64,<data>"),
+ ("unsupported_mine_type", "invalid_mine_prefix:image/png;base64,", "invalid MIME prefix format. Must start with 'data:'"),
("invalid_mine_type", "data:unsupported_mine_type;base64,", "Unsupported MIME type. Allowed: ['image/jpeg', 'image/png']"),
],
ids=["empty_prefix", "missing_comma", "unsupported_mine_type", "invalid_mine_type"],
@@ -276,9 +276,9 @@ class TestDatasetCreate:
res = create_dataset(HttpApiAuth, payload)
assert res["code"] == 101, res
if name in ["empty", "space", "missing_at"]:
- assert "Embedding model identifier must follow <model_name>@<provider> format" in res["message"], res
+ assert "embedding model identifier must follow <model_name>@<provider> format" in res["message"], res
else:
- assert "Both model_name and provider must be non-empty strings" in res["message"], res
+ assert "both model_name and provider must be non-empty strings" in res["message"], res
@pytest.mark.p2
def test_embedding_model_unset(self, HttpApiAuth):
diff --git a/test/testcases/test_http_api/test_dataset_management/test_update_dataset.py b/test/testcases/test_http_api/test_dataset_management/test_update_dataset.py
index c817f7533f..e18e99073c 100644
--- a/test/testcases/test_http_api/test_dataset_management/test_update_dataset.py
+++ b/test/testcases/test_http_api/test_dataset_management/test_update_dataset.py
@@ -214,9 +214,9 @@ class TestDatasetUpdate:
@pytest.mark.parametrize(
"avatar_prefix, expected_message",
[
- ("", "Missing MIME prefix. Expected format: data:<mime>;base64,<data>"),
- ("data:image/png;base64", "Missing MIME prefix. Expected format: data:<mime>;base64,<data>"),
- ("invalid_mine_prefix:image/png;base64,", "Invalid MIME prefix format. Must start with 'data:'"),
+ ("", "missing MIME prefix. Expected format: data:<mime>;base64,<data>"),
+ ("data:image/png;base64", "missing MIME prefix. Expected format: data:<mime>;base64,<data>"),
+ ("invalid_mine_prefix:image/png;base64,", "invalid MIME prefix format. Must start with 'data:'"),
("data:unsupported_mine_type;base64,", "Unsupported MIME type. Allowed: ['image/jpeg', 'image/png']"),
],
ids=["empty_prefix", "missing_comma", "unsupported_mine_type", "invalid_mine_type"],
@@ -349,9 +349,9 @@ class TestDatasetUpdate:
res = update_dataset(HttpApiAuth, dataset_id, payload)
assert res["code"] == 101, res
if name in ["empty", "space", "missing_at"]:
- assert "Embedding model identifier must follow <model_name>@<provider> format" in res["message"], res
+ assert "embedding model identifier must follow <model_name>@<provider> format" in res["message"], res
else:
- assert "Both model_name and provider must be non-empty strings" in res["message"], res
+ assert "both model_name and provider must be non-empty strings" in res["message"], res
@pytest.mark.p2
def test_embedding_model_none(self, HttpApiAuth, add_dataset_func):
diff --git a/test/testcases/test_http_api/test_file_app/test_file_routes.py b/test/testcases/test_http_api/test_file_app/test_file_routes.py
index 19c4a9876e..9998665b30 100644
--- a/test/testcases/test_http_api/test_file_app/test_file_routes.py
+++ b/test/testcases/test_http_api/test_file_app/test_file_routes.py
@@ -351,7 +351,7 @@ def test_get_file_content_checks_permission(monkeypatch):
ok, message = module.get_file_content("tenant1", "file1")
assert ok is False
- assert message == "No authorization."
+ assert message == "no authorization"
monkeypatch.setattr(module, "check_file_team_permission", lambda *_args, **_kwargs: True)
ok, file = module.get_file_content("tenant1", "file1")
diff --git a/test/testcases/test_http_api/test_file_management_within_dataset/test_update_document.py b/test/testcases/test_http_api/test_file_management_within_dataset/test_update_document.py
index de0b4189b9..3cfdae2296 100644
--- a/test/testcases/test_http_api/test_file_management_within_dataset/test_update_document.py
+++ b/test/testcases/test_http_api/test_file_management_within_dataset/test_update_document.py
@@ -103,7 +103,7 @@ class TestDocumentsUpdated:
(
INVALID_ID_32,
102,
- "The dataset doesn't own the document.",
+ "the dataset doesn't own the document",
),
],
)
@@ -120,7 +120,7 @@ class TestDocumentsUpdated:
(
INVALID_ID_32,
102,
- "You don't own the dataset.",
+ "you don't own the dataset",
),
],
)
@@ -167,7 +167,7 @@ class TestDocumentsUpdated:
"meta_fields, expected_code, expected_message",
[
# Test with invalid document ID (not owned by dataset)
- ({"author": "alice"}, 102, "The dataset doesn't own the document."),
+ ({"author": "alice"}, 102, "the dataset doesn't own the document"),
],
)
def test_meta_fields_invalid_document(self, HttpApiAuth, add_documents, meta_fields, expected_code, expected_message):
diff --git a/test/testcases/test_http_api/test_session_management/test_chat_completions.py b/test/testcases/test_http_api/test_session_management/test_chat_completions.py
index 0809dbeeeb..2582f503dc 100644
--- a/test/testcases/test_http_api/test_session_management/test_chat_completions.py
+++ b/test/testcases/test_http_api/test_session_management/test_chat_completions.py
@@ -86,7 +86,7 @@ class TestChatCompletions:
},
)
assert res["code"] == 109, res
- assert "No authorization." in res.get("message", ""), res
+ assert "no authorization" in res.get("message", ""), res
@pytest.mark.p2
def test_chat_completion_invalid_session(self, HttpApiAuth, request):
diff --git a/test/testcases/test_http_api/test_session_management/test_create_session_with_chat_assistant.py b/test/testcases/test_http_api/test_session_management/test_create_session_with_chat_assistant.py
index c91727b89d..e80566bfbe 100644
--- a/test/testcases/test_http_api/test_session_management/test_create_session_with_chat_assistant.py
+++ b/test/testcases/test_http_api/test_session_management/test_create_session_with_chat_assistant.py
@@ -45,7 +45,7 @@ class TestSessionWithChatAssistantCreate:
({"name": "valid_name"}, 0, ""),
pytest.param({"name": "a" * (SESSION_WITH_CHAT_NAME_LIMIT + 1)}, 102, "", marks=pytest.mark.skip(reason="issues/")),
pytest.param({"name": 1}, 100, "", marks=pytest.mark.skip(reason="issues/")),
- ({"name": ""}, 102, "`name` can not be empty."),
+ ({"name": ""}, 102, "`name` can not be empty"),
({"name": "duplicated_name"}, 0, ""),
({"name": "case insensitive"}, 0, ""),
],
@@ -70,7 +70,7 @@ class TestSessionWithChatAssistantCreate:
"chat_assistant_id, expected_code, expected_message",
[
("", 100, "<MethodNotAllowed '405: Method Not Allowed'>"),
- ("invalid_chat_assistant_id", 109, "No authorization."),
+ ("invalid_chat_assistant_id", 109, "no authorization"),
],
)
def test_invalid_chat_assistant_id(self, HttpApiAuth, chat_assistant_id, expected_code, expected_message):
@@ -112,4 +112,4 @@ class TestSessionWithChatAssistantCreate:
assert res["code"] == 0
res = create_session_with_chat_assistant(HttpApiAuth, chat_assistant_ids[0], {"name": "valid_name"})
assert res["code"] == 109
- assert res["message"] == "No authorization."
+ assert res["message"] == "no authorization"
diff --git a/test/testcases/test_http_api/test_session_management/test_delete_sessions_with_chat_assistant.py b/test/testcases/test_http_api/test_session_management/test_delete_sessions_with_chat_assistant.py
index 62f386ef17..d8044c55df 100644
--- a/test/testcases/test_http_api/test_session_management/test_delete_sessions_with_chat_assistant.py
+++ b/test/testcases/test_http_api/test_session_management/test_delete_sessions_with_chat_assistant.py
@@ -44,7 +44,7 @@ class TestSessionWithChatAssistantDelete:
(
"invalid_chat_assistant_id",
109,
- "No authorization.",
+ "no authorization",
),
],
)
diff --git a/test/testcases/test_http_api/test_session_management/test_list_sessions_with_chat_assistant.py b/test/testcases/test_http_api/test_session_management/test_list_sessions_with_chat_assistant.py
index 4d3d79c223..0ea46706f5 100644
--- a/test/testcases/test_http_api/test_session_management/test_list_sessions_with_chat_assistant.py
+++ b/test/testcases/test_http_api/test_session_management/test_list_sessions_with_chat_assistant.py
@@ -243,4 +243,4 @@ class TestSessionsWithChatAssistantList:
res = list_session_with_chat_assistants(HttpApiAuth, chat_assistant_id)
assert res["code"] == 109
- assert res["message"] == "No authorization."
+ assert res["message"] == "no authorization"
diff --git a/test/testcases/test_http_api/test_session_management/test_update_session_with_chat_assistant.py b/test/testcases/test_http_api/test_session_management/test_update_session_with_chat_assistant.py
index 7694c99c1b..dc294fc0d3 100644
--- a/test/testcases/test_http_api/test_session_management/test_update_session_with_chat_assistant.py
+++ b/test/testcases/test_http_api/test_session_management/test_update_session_with_chat_assistant.py
@@ -44,7 +44,7 @@ class TestSessionWithChatAssistantUpdate:
pytest.param({"name": "valid_name"}, 0, "", marks=pytest.mark.p1),
pytest.param({"name": "a" * (SESSION_WITH_CHAT_NAME_LIMIT + 1)}, 102, "", marks=pytest.mark.skip(reason="issues/")),
pytest.param({"name": 1}, 100, "", marks=pytest.mark.skip(reason="issues/")),
- pytest.param({"name": ""}, 102, "`name` can not be empty.", marks=pytest.mark.p3),
+ pytest.param({"name": ""}, 102, "`name` can not be empty", marks=pytest.mark.p3),
pytest.param({"name": "duplicated_name"}, 0, "", marks=pytest.mark.p3),
pytest.param({"name": "case insensitive"}, 0, "", marks=pytest.mark.p3),
],
@@ -68,7 +68,7 @@ class TestSessionWithChatAssistantUpdate:
@pytest.mark.parametrize(
"chat_assistant_id, expected_code, expected_message",
[
- (INVALID_ID_32, 109, "No authorization."),
+ (INVALID_ID_32, 109, "no authorization"),
],
)
def test_invalid_chat_assistant_id(self, HttpApiAuth, add_sessions_with_chat_assistant_func, chat_assistant_id, expected_code, expected_message):
@@ -142,4 +142,4 @@ class TestSessionWithChatAssistantUpdate:
delete_chat_assistants(HttpApiAuth, {"ids": [chat_assistant_id]})
res = update_session_with_chat_assistant(HttpApiAuth, chat_assistant_id, session_ids[0], {"name": "valid_name"})
assert res["code"] == 109
- assert res["message"] == "No authorization."
+ assert res["message"] == "no authorization"
diff --git a/test/testcases/test_sdk_api/test_chat_assistant_management/test_chat_crud_unit.py b/test/testcases/test_sdk_api/test_chat_assistant_management/test_chat_crud_unit.py
index 68805a1237..fe52e1d0da 100644
--- a/test/testcases/test_sdk_api/test_chat_assistant_management/test_chat_crud_unit.py
+++ b/test/testcases/test_sdk_api/test_chat_assistant_management/test_chat_crud_unit.py
@@ -47,12 +47,12 @@ def test_chat_create_session_raises_server_error_message(monkeypatch):
monkeypatch.setattr(
chat,
"post",
- lambda *_args, **_kwargs: _DummyResponse({"code": 102, "message": "`name` can not be empty."}),
+ lambda *_args, **_kwargs: _DummyResponse({"code": 102, "message": "`name` can not be empty"}),
)
with pytest.raises(Exception) as exception_info:
chat.create_session(name="")
- assert "`name` can not be empty." in str(exception_info.value), str(exception_info.value)
+ assert "`name` can not be empty" in str(exception_info.value), str(exception_info.value)
@pytest.mark.p2
diff --git a/test/testcases/test_sdk_api/test_chat_assistant_management/test_list_chat_assistants.py b/test/testcases/test_sdk_api/test_chat_assistant_management/test_list_chat_assistants.py
index 3387bd693c..79fbf3b4b5 100644
--- a/test/testcases/test_sdk_api/test_chat_assistant_management/test_list_chat_assistants.py
+++ b/test/testcases/test_sdk_api/test_chat_assistant_management/test_list_chat_assistants.py
@@ -178,7 +178,7 @@ class TestChatAssistantsList:
"chat_assistant_id, expected_message",
[
(lambda r: r[0], ""),
- ("unknown", "No authorization."),
+ ("unknown", "no authorization"),
],
)
def test_get_chat(self, client, add_chat_assistants, chat_assistant_id, expected_message):
diff --git a/test/testcases/test_sdk_api/test_dataset_mangement/test_create_dataset.py b/test/testcases/test_sdk_api/test_dataset_mangement/test_create_dataset.py
index 31fe5d2c06..7d0618b2b9 100644
--- a/test/testcases/test_sdk_api/test_dataset_mangement/test_create_dataset.py
+++ b/test/testcases/test_sdk_api/test_dataset_mangement/test_create_dataset.py
@@ -94,7 +94,7 @@ class TestDatasetCreate:
if name == "":
expected_message = "failed on the 'required' tag"
elif isinstance(name, str) and not name.strip():
- expected_message = "Dataset name can't be empty."
+ expected_message = "dataset name can't be empty"
elif isinstance(name, str):
expected_message = f"Dataset name length is {len(name)} which is large than {DATASET_NAME_LIMIT}"
assert expected_message in str(exception_info.value), str(exception_info.value)
@@ -138,9 +138,9 @@ class TestDatasetCreate:
@pytest.mark.parametrize(
"name, prefix, expected_message",
[
- ("empty_prefix", "", "Missing MIME prefix. Expected format: data:<mime>;base64,<data>"),
- ("missing_comma", "data:image/png;base64", "Missing MIME prefix. Expected format: data:<mime>;base64,<data>"),
- ("unsupported_mine_type", "invalid_mine_prefix:image/png;base64,", "Invalid MIME prefix format. Must start with 'data:'"),
+ ("empty_prefix", "", "missing MIME prefix. Expected format: data:<mime>;base64,<data>"),
+ ("missing_comma", "data:image/png;base64", "missing MIME prefix. Expected format: data:<mime>;base64,<data>"),
+ ("unsupported_mine_type", "invalid_mine_prefix:image/png;base64,", "invalid MIME prefix format. Must start with 'data:'"),
("invalid_mine_type", "data:unsupported_mine_type;base64,", "Unsupported MIME type. Allowed: ['image/jpeg', 'image/png']"),
],
ids=["empty_prefix", "missing_comma", "unsupported_mine_type", "invalid_mine_type"],
@@ -236,9 +236,9 @@ class TestDatasetCreate:
with pytest.raises(Exception) as exception_info:
client.create_dataset(**payload)
if name in ["empty", "space", "missing_at"]:
- assert "Embedding model identifier must follow <model_name>@<provider> format" in str(exception_info.value), str(exception_info.value)
+ assert "embedding model identifier must follow <model_name>@<provider> format" in str(exception_info.value), str(exception_info.value)
else:
- assert "Both model_name and provider must be non-empty strings" in str(exception_info.value), str(exception_info.value)
+ assert "both model_name and provider must be non-empty strings" in str(exception_info.value), str(exception_info.value)
@pytest.mark.p2
def test_embedding_model_unset(self, client):
diff --git a/test/testcases/test_sdk_api/test_dataset_mangement/test_update_dataset.py b/test/testcases/test_sdk_api/test_dataset_mangement/test_update_dataset.py
index 2a5b2c1d42..7fe6a69ea5 100644
--- a/test/testcases/test_sdk_api/test_dataset_mangement/test_update_dataset.py
+++ b/test/testcases/test_sdk_api/test_dataset_mangement/test_update_dataset.py
@@ -125,9 +125,9 @@ class TestDatasetUpdate:
@pytest.mark.parametrize(
"avatar_prefix, expected_message",
[
- ("", "Missing MIME prefix. Expected format: data:<mime>;base64,<data>"),
- ("data:image/png;base64", "Missing MIME prefix. Expected format: data:<mime>;base64,<data>"),
- ("invalid_mine_prefix:image/png;base64,", "Invalid MIME prefix format. Must start with 'data:'"),
+ ("", "missing MIME prefix. Expected format: data:<mime>;base64,<data>"),
+ ("data:image/png;base64", "missing MIME prefix. Expected format: data:<mime>;base64,<data>"),
+ ("invalid_mine_prefix:image/png;base64,", "invalid MIME prefix format. Must start with 'data:'"),
("data:unsupported_mine_type;base64,", "Unsupported MIME type. Allowed: ['image/jpeg', 'image/png']"),
],
ids=["empty_prefix", "missing_comma", "unsupported_mine_type", "invalid_mine_type"],
@@ -230,9 +230,9 @@ class TestDatasetUpdate:
if IS_GO_PROXY and name in ["empty", "space"]:
assert "lookup failed: record not found" in error_msg, error_msg
elif name in ["empty", "space", "missing_at"]:
- assert "Embedding model identifier must follow <model_name>@<provider> format" in error_msg, error_msg
+ assert "embedding model identifier must follow <model_name>@<provider> format" in error_msg, error_msg
else:
- assert "Both model_name and provider must be non-empty strings" in error_msg, error_msg
+ assert "both model_name and provider must be non-empty strings" in error_msg, error_msg
@pytest.mark.p2
def test_embedding_model_none(self, client, add_dataset_func):
diff --git a/test/testcases/test_sdk_api/test_session_management/test_create_session_with_chat_assistant.py b/test/testcases/test_sdk_api/test_session_management/test_create_session_with_chat_assistant.py
index 6046f21ce7..1e0ded1576 100644
--- a/test/testcases/test_sdk_api/test_session_management/test_create_session_with_chat_assistant.py
+++ b/test/testcases/test_sdk_api/test_session_management/test_create_session_with_chat_assistant.py
@@ -41,7 +41,7 @@ class TestSessionWithChatAssistantCreate:
("valid_name", ""),
pytest.param("a" * (SESSION_WITH_CHAT_NAME_LIMIT + 1), "", marks=pytest.mark.skip(reason="issues/")),
pytest.param(1, "", marks=pytest.mark.skip(reason="issues/")),
- ("", "`name` can not be empty."),
+ ("", "`name` can not be empty"),
("duplicated_name", ""),
("case insensitive", ""),
],
@@ -86,7 +86,7 @@ class TestSessionWithChatAssistantCreate:
client.delete_chats(ids=[chat_assistant.id])
with pytest.raises(Exception) as exception_info:
chat_assistant.create_session(name="valid_name")
- assert "No authorization." in str(exception_info.value)
+ assert "no authorization" in str(exception_info.value)
@pytest.mark.p2
diff --git a/test/testcases/test_sdk_api/test_session_management/test_list_sessions_with_chat_assistant.py b/test/testcases/test_sdk_api/test_session_management/test_list_sessions_with_chat_assistant.py
index f22aa909a7..48743e4be7 100644
--- a/test/testcases/test_sdk_api/test_session_management/test_list_sessions_with_chat_assistant.py
+++ b/test/testcases/test_sdk_api/test_session_management/test_list_sessions_with_chat_assistant.py
@@ -227,7 +227,7 @@ class TestSessionsWithChatAssistantList:
with pytest.raises(Exception) as exception_info:
chat_assistant.list_sessions()
- assert "No authorization." in str(exception_info.value)
+ assert "no authorization" in str(exception_info.value)
@pytest.mark.p2
diff --git a/test/testcases/test_sdk_api/test_session_management/test_update_session_with_chat_assistant.py b/test/testcases/test_sdk_api/test_session_management/test_update_session_with_chat_assistant.py
index 10e0b72633..b92cc11eb9 100644
--- a/test/testcases/test_sdk_api/test_session_management/test_update_session_with_chat_assistant.py
+++ b/test/testcases/test_sdk_api/test_session_management/test_update_session_with_chat_assistant.py
@@ -27,7 +27,7 @@ class TestSessionWithChatAssistantUpdate:
pytest.param({"name": "valid_name"}, "", marks=pytest.mark.p3),
pytest.param({"name": "a" * (SESSION_WITH_CHAT_NAME_LIMIT + 1)}, "", marks=pytest.mark.skip(reason="issues/")),
pytest.param({"name": 1}, "", marks=pytest.mark.skip(reason="issues/")),
- pytest.param({"name": ""}, "`name` can not be empty.", marks=pytest.mark.p3),
+ pytest.param({"name": ""}, "`name` can not be empty", marks=pytest.mark.p3),
pytest.param({"name": "duplicated_name"}, "", marks=pytest.mark.p3),
pytest.param({"name": "case insensitive"}, "", marks=pytest.mark.p3),
],
@@ -95,4 +95,4 @@ class TestSessionWithChatAssistantUpdate:
with pytest.raises(Exception) as exception_info:
sessions[0].update({"name": "valid_name"})
- assert "No authorization." in str(exception_info.value)
+ assert "no authorization" in str(exception_info.value)
diff --git a/test/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py b/test/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py
index 580a8397ae..6f485af334 100644
--- a/test/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py
+++ b/test/testcases/test_web_api/test_connector_app/test_connector_routes_unit.py
@@ -446,7 +446,7 @@ def test_connector_by_id_routes_reject_cross_tenant_access(monkeypatch):
]
assert all(res["code"] == module.RetCode.AUTHENTICATION_ERROR for res in responses)
- assert all(res["message"] == "No authorization." for res in responses)
+ assert all(res["message"] == "no authorization" for res in responses)
assert all(res["data"] is False for res in responses)
assert touched == []
diff --git a/test/testcases/test_web_api/test_document_app/test_document_metadata.py b/test/testcases/test_web_api/test_document_app/test_document_metadata.py
index 0d5fb3fb02..badc951ca3 100644
--- a/test/testcases/test_web_api/test_document_app/test_document_metadata.py
+++ b/test/testcases/test_web_api/test_document_app/test_document_metadata.py
@@ -256,7 +256,7 @@ class TestDocumentMetadataNegative:
# Now try to update metadata setting for the deleted document
res = document_update_metadata_setting(WebApiAuth, dataset_id, doc_id, {"metadata": {"author": "test"}})
assert res["code"] == 102, res
- assert f"Document {doc_id} not found in dataset {dataset_id}" in res["message"], res
+ assert f"document {doc_id} not found in dataset {dataset_id}" in res["message"], res
@pytest.mark.p3
def test_change_status_invalid_status(self, WebApiAuth, add_document_func):
diff --git a/test/testcases/test_web_api/test_document_app/test_paser_documents.py b/test/testcases/test_web_api/test_document_app/test_paser_documents.py
index e3b0c00839..abc3b038c3 100644
--- a/test/testcases/test_web_api/test_document_app/test_paser_documents.py
+++ b/test/testcases/test_web_api/test_document_app/test_paser_documents.py
@@ -88,8 +88,8 @@ class TestDocumentsParse:
[
pytest.param(None, 101, "required argument are missing: doc_ids, run; ", marks=pytest.mark.skip),
pytest.param({"doc_ids": [], "run": "1"}, 0, "", marks=pytest.mark.p1),
- pytest.param({"doc_ids": ["invalid_id"], "run": "1"}, 109, "No authorization.", marks=pytest.mark.p3),
- pytest.param({"doc_ids": ["\n!?。;!?\"'"], "run": "1"}, 109, "No authorization.", marks=pytest.mark.p3),
+ pytest.param({"doc_ids": ["invalid_id"], "run": "1"}, 109, "no authorization", marks=pytest.mark.p3),
+ pytest.param({"doc_ids": ["\n!?。;!?\"'"], "run": "1"}, 109, "no authorization", marks=pytest.mark.p3),
pytest.param("not json", 101, "required argument are missing: doc_ids, run; ", marks=pytest.mark.skip),
pytest.param(lambda r: {"doc_ids": r[:1], "run": "1"}, 0, "", marks=pytest.mark.p1),
pytest.param(lambda r: {"doc_ids": r, "run": "1"}, 0, "", marks=pytest.mark.p1),
@@ -121,7 +121,7 @@ class TestDocumentsParse:
payload = payload(document_ids)
res = parse_documents(WebApiAuth, payload)
assert res["code"] == 109, res
- assert res["message"] == "No authorization.", res
+ assert res["message"] == "no authorization", res
@pytest.mark.p2
def test_document_not_found(self, WebApiAuth, add_documents_func):
@@ -301,8 +301,8 @@ class TestDocumentsParseStop:
[
pytest.param(None, 101, "required argument are missing: doc_ids, run; ", marks=pytest.mark.skip),
pytest.param({"doc_ids": [], "run": "2"}, 0, "", marks=pytest.mark.p1),
- pytest.param({"doc_ids": ["invalid_id"], "run": "2"}, 109, "No authorization.", marks=pytest.mark.p3),
- pytest.param({"doc_ids": ["\n!?。;!?\"'"], "run": "2"}, 109, "No authorization.", marks=pytest.mark.p3),
+ pytest.param({"doc_ids": ["invalid_id"], "run": "2"}, 109, "no authorization", marks=pytest.mark.p3),
+ pytest.param({"doc_ids": ["\n!?。;!?\"'"], "run": "2"}, 109, "no authorization", marks=pytest.mark.p3),
pytest.param("not json", 101, "required argument are missing: doc_ids, run; ", marks=pytest.mark.skip),
pytest.param(lambda r: {"doc_ids": r[:1], "run": "2"}, 0, "", marks=pytest.mark.p1),
pytest.param(lambda r: {"doc_ids": r, "run": "2"}, 0, "", marks=pytest.mark.p1),
@@ -351,6 +351,6 @@ class TestDocumentsParseStop:
payload = payload(document_ids)
res = parse_documents(WebApiAuth, payload)
assert res["code"] == 109, res
- assert res["message"] == "No authorization.", res
+ assert res["message"] == "no authorization", res
validate_document_parse_cancel(WebApiAuth, kb_id, document_ids)
diff --git a/test/testcases/test_web_api/test_document_app/test_upload_documents.py b/test/testcases/test_web_api/test_document_app/test_upload_documents.py
index f0bc07b07c..0abd99246c 100644
--- a/test/testcases/test_web_api/test_document_app/test_upload_documents.py
+++ b/test/testcases/test_web_api/test_document_app/test_upload_documents.py
@@ -355,7 +355,7 @@ class TestWebCrawlUnit:
)
res = _run(module.upload_document(dataset_id="kb1"))
assert res["code"] == 109
- assert res["message"] == "No authorization."
+ assert res["message"] == "no authorization"
def test_download_failure(self, document_rest_api_module, monkeypatch):
module = document_rest_api_module
diff --git a/test/testcases/test_web_api/test_file_app/test_file2document_routes_unit.py b/test/testcases/test_web_api/test_file_app/test_file2document_routes_unit.py
index 8d014cf231..f593ac4efa 100644
--- a/test/testcases/test_web_api/test_file_app/test_file2document_routes_unit.py
+++ b/test/testcases/test_web_api/test_file_app/test_file2document_routes_unit.py
@@ -273,13 +273,13 @@ def test_convert_branch_matrix_unit(monkeypatch):
# Unauthorized file access is rejected before scheduling background work.
monkeypatch.setattr(module, "check_file_team_permission", lambda *_args, **_kwargs: False)
res = _run(module.convert())
- assert res["message"] == "No authorization."
+ assert res["message"] == "no authorization"
# Unauthorized dataset access is rejected before scheduling background work.
monkeypatch.setattr(module, "check_file_team_permission", lambda *_args, **_kwargs: True)
monkeypatch.setattr(module, "check_kb_team_permission", lambda *_args, **_kwargs: False)
res = _run(module.convert())
- assert res["message"] == "No authorization."
+ assert res["message"] == "no authorization"
# Valid file and kb schedule background work and return data=True immediately.
monkeypatch.setattr(module, "check_kb_team_permission", lambda *_args, **_kwargs: True)
diff --git a/test/testcases/test_web_api/test_user_app/test_tenant_app_unit.py b/test/testcases/test_web_api/test_user_app/test_tenant_app_unit.py
index d9a99e0e3c..1fc6077025 100644
--- a/test/testcases/test_web_api/test_user_app/test_tenant_app_unit.py
+++ b/test/testcases/test_web_api/test_user_app/test_tenant_app_unit.py
@@ -196,7 +196,7 @@ def test_user_list_auth_success_exception_matrix_unit(monkeypatch):
module.current_user.id = "other-user"
res = module.user_list("tenant-1")
assert res["code"] == module.RetCode.AUTHENTICATION_ERROR, res
- assert res["message"] == "No authorization.", res
+ assert res["message"] == "no authorization", res
module.current_user.id = "tenant-1"
monkeypatch.setattr(
@@ -223,7 +223,7 @@ def test_create_invite_role_and_email_failure_matrix_unit(monkeypatch):
_set_request_json(monkeypatch, module, {"email": "[email protected]"})
res = _run(module.create("tenant-1"))
assert res["code"] == module.RetCode.AUTHENTICATION_ERROR, res
- assert res["message"] == "No authorization.", res
+ assert res["message"] == "no authorization", res
module.current_user.id = "tenant-1"
monkeypatch.setattr(module.UserService, "query", lambda **_kwargs: [])
@@ -271,7 +271,7 @@ def test_rm_and_tenant_list_matrix_unit(monkeypatch):
_set_request_json(monkeypatch, module, {"user_id": "user-2"})
res = _run(module.rm("tenant-1"))
assert res["code"] == module.RetCode.AUTHENTICATION_ERROR, res
- assert res["message"] == "No authorization.", res
+ assert res["message"] == "no authorization", res
module.current_user.id = "tenant-1"
deleted = []
diff --git a/web/src/locales/en.ts b/web/src/locales/en.ts
index e2030651d7..ddf0bf42e6 100644
--- a/web/src/locales/en.ts
+++ b/web/src/locales/en.ts
@@ -1994,7 +1994,7 @@ Example: Virtual Hosted Style`,
timezoneMessage: 'Please input your timezone!',
timezonePlaceholder: 'select your timezone',
email: 'Email',
- emailDescription: 'Once registered, E-mail cannot be changed.',
+ emailDescription: 'Once registered, E-mail cannot be changed',
currentPassword: 'Current password',
currentPasswordMessage: 'Please input your password!',
newPassword: 'New password',