2025-11-08 16:02:31 +00:00
|
|
|
|
package session
|
|
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
|
"context"
|
fix(session): map ErrSessionNotFound to 404 across all handlers
PR #1309 plumbed user-scope into the session/message service layer so
non-owner / wrong-tenant lookups now surface as ErrSessionNotFound at
every entry point that goes through sessionRepo.Get. The handler-side
mapping, however, only existed in 4 of the 8 affected sites:
- handler/session/handler.go:GetSession ✓ already mapped (with `==`)
- handler/session/handler.go:UpdateSession ✓ already mapped (with `==`)
- handler/session/handler.go:DeleteSession ✓ already mapped (with `==`)
- handler/session/handler.go:BatchDeleteSessions ✓ already mapped (with `==`)
- handler/session/handler.go:ClearSessionMessages ✗ always 500
- handler/session/stream.go:ContinueStream session lookup ✓ (with `==`)
- handler/session/stream.go:ContinueStream message lookup ✗ always 500
- handler/message.go:LoadMessages (recent + before-time) ✗ always 500
- handler/message.go:DeleteMessage ✗ always 500
Result: a Contributor in tenant A asking for a Contributor B's session
messages got a 500 instead of 404 — the wire response leaked
"something is broken" rather than "you can't see this URL", which
breaks SDK / frontend axios interceptor error handling that keys on
HTTP status.
Two changes:
1. Add ErrSessionNotFound → 404 mapping to the 4 sites that lacked it
(ClearSessionMessages, ContinueStream's GetMessage, LoadMessages's
two paths, DeleteMessage).
2. Replace `err == errors.ErrSessionNotFound` with
`stderrors.Is(err, errors.ErrSessionNotFound)` everywhere. Sentinel
error comparison must use errors.Is so wrapped errors
(`fmt.Errorf("...: %w", ErrSessionNotFound)`) still match. Today no
service-layer caller wraps, but a future refactor that does would
silently turn 404s into 500s with no test catching it.
Tests:
- internal/handler/message_session_not_found_test.go covers the four
new mapping sites in handler/message.go (LoadMessages-recent,
LoadMessages-before-time, DeleteMessage) and pins the wrapped-error
behaviour with a dedicated regression test that fmt.Errorf("%w") a
sentinel must still be detected as ErrSessionNotFound. The bare
handler is hit through gin.Engine + middleware.ErrorHandler so the
response shape matches production exactly.
- PR #1309's existing service-level tests (session_user_scope_test,
session_test on the repository) still pass — this PR is a strictly
handler-layer follow-up.
2026-05-14 08:44:55 +00:00
|
|
|
|
stderrors "errors"
|
2025-11-08 16:02:31 +00:00
|
|
|
|
"fmt"
|
|
|
|
|
|
"net/http"
|
|
|
|
|
|
"time"
|
|
|
|
|
|
|
|
|
|
|
|
"github.com/Tencent/WeKnora/internal/errors"
|
|
|
|
|
|
"github.com/Tencent/WeKnora/internal/event"
|
|
|
|
|
|
"github.com/Tencent/WeKnora/internal/logger"
|
2026-08-04 09:14:52 +00:00
|
|
|
|
"github.com/Tencent/WeKnora/internal/storageurl"
|
2025-11-08 16:02:31 +00:00
|
|
|
|
"github.com/Tencent/WeKnora/internal/types"
|
|
|
|
|
|
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
2025-11-26 05:14:29 +00:00
|
|
|
|
secutils "github.com/Tencent/WeKnora/internal/utils"
|
2025-11-08 16:02:31 +00:00
|
|
|
|
"github.com/gin-gonic/gin"
|
2026-06-26 12:40:59 +00:00
|
|
|
|
"gorm.io/gorm"
|
2025-11-08 16:02:31 +00:00
|
|
|
|
)
|
|
|
|
|
|
|
2025-12-16 08:40:13 +00:00
|
|
|
|
// ContinueStream godoc
|
|
|
|
|
|
// @Summary 继续流式响应
|
|
|
|
|
|
// @Description 继续获取正在进行的流式响应
|
|
|
|
|
|
// @Tags 问答
|
|
|
|
|
|
// @Accept json
|
|
|
|
|
|
// @Produce text/event-stream
|
2026-08-04 09:29:27 +00:00
|
|
|
|
// @Param session_id path string true "会话ID"
|
|
|
|
|
|
// @Param message_id query string true "消息ID"
|
|
|
|
|
|
// @Param resource_urls query string false "文件引用形式,public 返回可加载直链" Enums(handle, public) default(handle)
|
|
|
|
|
|
// @Success 200 {object} map[string]interface{} "流式响应"
|
2025-12-16 08:40:13 +00:00
|
|
|
|
// @Failure 404 {object} errors.AppError "会话或消息不存在"
|
|
|
|
|
|
// @Security Bearer
|
2025-12-22 06:36:29 +00:00
|
|
|
|
// @Security ApiKeyAuth
|
2026-05-11 09:37:14 +00:00
|
|
|
|
// @Router /sessions/continue-stream/{session_id} [get]
|
2025-11-08 16:02:31 +00:00
|
|
|
|
func (h *Handler) ContinueStream(c *gin.Context) {
|
|
|
|
|
|
ctx := c.Request.Context()
|
|
|
|
|
|
|
|
|
|
|
|
logger.Info(ctx, "Start continuing stream response processing")
|
|
|
|
|
|
|
|
|
|
|
|
// Get session ID from URL parameter
|
2025-11-26 05:14:29 +00:00
|
|
|
|
sessionID := secutils.SanitizeForLog(c.Param("session_id"))
|
2025-11-08 16:02:31 +00:00
|
|
|
|
if sessionID == "" {
|
|
|
|
|
|
logger.Error(ctx, "Session ID is empty")
|
|
|
|
|
|
c.Error(errors.NewBadRequestError(errors.ErrInvalidSessionID.Error()))
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Get message ID from query parameter
|
2025-11-26 05:14:29 +00:00
|
|
|
|
messageID := secutils.SanitizeForLog(c.Query("message_id"))
|
2025-11-08 16:02:31 +00:00
|
|
|
|
if messageID == "" {
|
|
|
|
|
|
logger.Error(ctx, "Message ID is empty")
|
|
|
|
|
|
c.Error(errors.NewBadRequestError("Missing message ID"))
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
logger.Infof(ctx, "Continuing stream, session ID: %s, message ID: %s", sessionID, messageID)
|
|
|
|
|
|
|
2026-08-04 09:14:52 +00:00
|
|
|
|
// Resolve before any SSE header is written so an invalid resource_urls value
|
|
|
|
|
|
// is still reportable as a normal 400 JSON error.
|
|
|
|
|
|
resourceRewriter, err := h.resolveStreamRewriter(c)
|
2025-11-08 16:02:31 +00:00
|
|
|
|
if err != nil {
|
fix(api): close the resource_urls=public gaps found in review
Follow-up on resource_urls=public. Review turned up one authorization gap plus a
set of correctness problems in the streaming path.
Authorization:
- Embed channels were documented as excluded, but nothing enforced it. The
delegating handlers hand the visitor's own gin context to the shared
handlers, so ?resource_urls=public — and a deployment-wide
RESOURCE_URL_MODE=public — reached anonymous traffic and produced
shareable, credential-free URLs that bypass the channel-scoped
/embed/:channel_id/files proxy. ensureEmbedSession now pins the request
context to handle mode, which covers every delegated endpoint including
future ones. The downgrade is silent so a client that forwards the
parameter keeps working.
- A knowledge-base-restricted API key is refused with 403. Such a key is
already denied /files because a raw storage path cannot be bound to its
allow-list, so handing it anonymous file URLs would reopen that hole from
the other side. The default handle mode stays available to it.
Streaming:
- Rewriter.ref holds its lock across resolution. Resolver implementations keep
an unsynchronised per-provider cache, so the previous unlocked window was a
real data race for any caller sharing a StreamRewriter between goroutines —
which its own doc comment invited. Serialising also collapses a concurrent
duplicate into one signature.
- Release the holdback buffer on every path that ends a stream while the
client is still connected: a user-requested stop, an error event, and
giving up on the event store. Only completion flushed before, so the tail
generated just before a stop was silently dropped.
- A released tail carries the metadata of the event it was cut from instead of
a bare event_id.
- The maxHeldBytes safety valve aligns to a UTF-8 boundary rather than cutting
a character in half, and an unclosed "
|
|
|
|
|
|
_ = c.Error(err)
|
2026-08-04 09:14:52 +00:00
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Verify that the session exists and belongs to this tenant
|
|
|
|
|
|
if _, err := h.sessionService.GetSession(ctx, sessionID); err != nil {
|
fix(session): map ErrSessionNotFound to 404 across all handlers
PR #1309 plumbed user-scope into the session/message service layer so
non-owner / wrong-tenant lookups now surface as ErrSessionNotFound at
every entry point that goes through sessionRepo.Get. The handler-side
mapping, however, only existed in 4 of the 8 affected sites:
- handler/session/handler.go:GetSession ✓ already mapped (with `==`)
- handler/session/handler.go:UpdateSession ✓ already mapped (with `==`)
- handler/session/handler.go:DeleteSession ✓ already mapped (with `==`)
- handler/session/handler.go:BatchDeleteSessions ✓ already mapped (with `==`)
- handler/session/handler.go:ClearSessionMessages ✗ always 500
- handler/session/stream.go:ContinueStream session lookup ✓ (with `==`)
- handler/session/stream.go:ContinueStream message lookup ✗ always 500
- handler/message.go:LoadMessages (recent + before-time) ✗ always 500
- handler/message.go:DeleteMessage ✗ always 500
Result: a Contributor in tenant A asking for a Contributor B's session
messages got a 500 instead of 404 — the wire response leaked
"something is broken" rather than "you can't see this URL", which
breaks SDK / frontend axios interceptor error handling that keys on
HTTP status.
Two changes:
1. Add ErrSessionNotFound → 404 mapping to the 4 sites that lacked it
(ClearSessionMessages, ContinueStream's GetMessage, LoadMessages's
two paths, DeleteMessage).
2. Replace `err == errors.ErrSessionNotFound` with
`stderrors.Is(err, errors.ErrSessionNotFound)` everywhere. Sentinel
error comparison must use errors.Is so wrapped errors
(`fmt.Errorf("...: %w", ErrSessionNotFound)`) still match. Today no
service-layer caller wraps, but a future refactor that does would
silently turn 404s into 500s with no test catching it.
Tests:
- internal/handler/message_session_not_found_test.go covers the four
new mapping sites in handler/message.go (LoadMessages-recent,
LoadMessages-before-time, DeleteMessage) and pins the wrapped-error
behaviour with a dedicated regression test that fmt.Errorf("%w") a
sentinel must still be detected as ErrSessionNotFound. The bare
handler is hit through gin.Engine + middleware.ErrorHandler so the
response shape matches production exactly.
- PR #1309's existing service-level tests (session_user_scope_test,
session_test on the repository) still pass — this PR is a strictly
handler-layer follow-up.
2026-05-14 08:44:55 +00:00
|
|
|
|
if stderrors.Is(err, errors.ErrSessionNotFound) {
|
2025-11-08 16:02:31 +00:00
|
|
|
|
logger.Warnf(ctx, "Session not found, ID: %s", sessionID)
|
|
|
|
|
|
c.Error(errors.NewNotFoundError(err.Error()))
|
|
|
|
|
|
} else {
|
|
|
|
|
|
logger.ErrorWithFields(ctx, err, nil)
|
|
|
|
|
|
c.Error(errors.NewInternalServerError(err.Error()))
|
|
|
|
|
|
}
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Get the incomplete message
|
|
|
|
|
|
message, err := h.messageService.GetMessage(ctx, sessionID, messageID)
|
|
|
|
|
|
if err != nil {
|
fix(session): map ErrSessionNotFound to 404 across all handlers
PR #1309 plumbed user-scope into the session/message service layer so
non-owner / wrong-tenant lookups now surface as ErrSessionNotFound at
every entry point that goes through sessionRepo.Get. The handler-side
mapping, however, only existed in 4 of the 8 affected sites:
- handler/session/handler.go:GetSession ✓ already mapped (with `==`)
- handler/session/handler.go:UpdateSession ✓ already mapped (with `==`)
- handler/session/handler.go:DeleteSession ✓ already mapped (with `==`)
- handler/session/handler.go:BatchDeleteSessions ✓ already mapped (with `==`)
- handler/session/handler.go:ClearSessionMessages ✗ always 500
- handler/session/stream.go:ContinueStream session lookup ✓ (with `==`)
- handler/session/stream.go:ContinueStream message lookup ✗ always 500
- handler/message.go:LoadMessages (recent + before-time) ✗ always 500
- handler/message.go:DeleteMessage ✗ always 500
Result: a Contributor in tenant A asking for a Contributor B's session
messages got a 500 instead of 404 — the wire response leaked
"something is broken" rather than "you can't see this URL", which
breaks SDK / frontend axios interceptor error handling that keys on
HTTP status.
Two changes:
1. Add ErrSessionNotFound → 404 mapping to the 4 sites that lacked it
(ClearSessionMessages, ContinueStream's GetMessage, LoadMessages's
two paths, DeleteMessage).
2. Replace `err == errors.ErrSessionNotFound` with
`stderrors.Is(err, errors.ErrSessionNotFound)` everywhere. Sentinel
error comparison must use errors.Is so wrapped errors
(`fmt.Errorf("...: %w", ErrSessionNotFound)`) still match. Today no
service-layer caller wraps, but a future refactor that does would
silently turn 404s into 500s with no test catching it.
Tests:
- internal/handler/message_session_not_found_test.go covers the four
new mapping sites in handler/message.go (LoadMessages-recent,
LoadMessages-before-time, DeleteMessage) and pins the wrapped-error
behaviour with a dedicated regression test that fmt.Errorf("%w") a
sentinel must still be detected as ErrSessionNotFound. The bare
handler is hit through gin.Engine + middleware.ErrorHandler so the
response shape matches production exactly.
- PR #1309's existing service-level tests (session_user_scope_test,
session_test on the repository) still pass — this PR is a strictly
handler-layer follow-up.
2026-05-14 08:44:55 +00:00
|
|
|
|
if stderrors.Is(err, errors.ErrSessionNotFound) {
|
|
|
|
|
|
// PR #1309 plumbed user-scope into messageService.GetMessage's
|
|
|
|
|
|
// session existence check; non-owner / wrong-user lookups now
|
|
|
|
|
|
// surface as ErrSessionNotFound. Map to 404 so clients can tell
|
|
|
|
|
|
// "wrong URL" from a real 5xx instead of seeing a generic 500.
|
|
|
|
|
|
logger.Warnf(ctx, "Session not found, ID: %s", sessionID)
|
|
|
|
|
|
c.Error(errors.NewNotFoundError(err.Error()))
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
2026-06-26 12:40:59 +00:00
|
|
|
|
if stderrors.Is(err, gorm.ErrRecordNotFound) {
|
|
|
|
|
|
// The message_id doesn't exist (e.g. a wrong / non-persisted id, or an
|
|
|
|
|
|
// expired replay buffer). That is a client error, not a server fault:
|
|
|
|
|
|
// return 404 so callers read resource.not_found (a permanent condition
|
|
|
|
|
|
// they must not retry) instead of a retryable 5xx. Mirrors the
|
|
|
|
|
|
// ErrSessionNotFound branch above and the kb/doc/chunk not-found fix.
|
|
|
|
|
|
logger.Warnf(ctx, "Message not found, session ID: %s, message ID: %s", sessionID, messageID)
|
|
|
|
|
|
c.Error(errors.NewNotFoundError(err.Error()))
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
2025-11-08 16:02:31 +00:00
|
|
|
|
logger.ErrorWithFields(ctx, err, nil)
|
|
|
|
|
|
c.Error(errors.NewInternalServerError(err.Error()))
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if message == nil {
|
|
|
|
|
|
logger.Warnf(ctx, "Incomplete message not found, session ID: %s, message ID: %s", sessionID, messageID)
|
|
|
|
|
|
c.JSON(http.StatusNotFound, gin.H{
|
|
|
|
|
|
"success": false,
|
|
|
|
|
|
"error": "Incomplete message not found",
|
|
|
|
|
|
})
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Get initial events from stream (offset 0)
|
|
|
|
|
|
events, currentOffset, err := h.streamManager.GetEvents(ctx, sessionID, messageID, 0)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
logger.ErrorWithFields(ctx, err, nil)
|
|
|
|
|
|
c.Error(errors.NewInternalServerError(fmt.Sprintf("Failed to get stream data: %s", err.Error())))
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if len(events) == 0 {
|
|
|
|
|
|
logger.Warnf(ctx, "No events found in stream, session ID: %s, message ID: %s", sessionID, messageID)
|
|
|
|
|
|
c.JSON(http.StatusNotFound, gin.H{
|
|
|
|
|
|
"success": false,
|
|
|
|
|
|
"error": "No stream events found",
|
|
|
|
|
|
})
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
logger.Infof(
|
|
|
|
|
|
ctx, "Preparing to replay %d events and continue streaming, session ID: %s, message ID: %s",
|
|
|
|
|
|
len(events), sessionID, messageID,
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
// Set headers for SSE
|
|
|
|
|
|
setSSEHeaders(c)
|
|
|
|
|
|
|
|
|
|
|
|
// Check if stream is already completed
|
|
|
|
|
|
streamCompleted := false
|
|
|
|
|
|
for _, evt := range events {
|
|
|
|
|
|
if evt.Type == "complete" {
|
|
|
|
|
|
streamCompleted = true
|
|
|
|
|
|
break
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
perf(chat): replay a stored stream a segment at a time
continue-stream replays every stored event as its own SSE frame, and
events are stored at the granularity the model emits them: one chunk per
AppendEvent, no accumulation. A long answer with a dozen length-limited
continuations is tens of thousands of chunks, and every reconnect during
it (a refresh, a re-entered page) replays them all, one write, one flush
and one client-side pass each; the report on #3362 counts 47,196 events
for a single replay, with the page frozen while they arrive.
Coalesce them on the way out. Each run of consecutive, unfinished
thinking or answer chunks of one segment (same type and event ID) is
replayed as one event carrying the run's concatenated content, its last
timestamp and the union of its data. A done chunk, a chunk of another
type or of another segment ends the run and passes through untouched:
the client marks a segment finished on its done chunk without appending
that chunk's content, and it accumulates content by event_id, so what it
assembles is the same text in the same order, in a few frames per
segment instead of one per token. The live path, the stored events and
the completion marker are unchanged.
2026-09-17 11:50:31 +00:00
|
|
|
|
// Replay existing events, a segment's worth of chunks per frame
|
|
|
|
|
|
replay := coalesceReplayEvents(events)
|
|
|
|
|
|
logger.Debugf(ctx, "Replaying %d existing events as %d frames", len(events), len(replay))
|
|
|
|
|
|
for _, evt := range replay {
|
2026-08-04 09:14:52 +00:00
|
|
|
|
emitStreamEvent(ctx, c, evt, message.RequestID, resourceRewriter)
|
2025-11-08 16:02:31 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// If stream is already completed, send final event and return
|
|
|
|
|
|
if streamCompleted {
|
|
|
|
|
|
logger.Infof(ctx, "Stream already completed, session ID: %s, message ID: %s", sessionID, messageID)
|
|
|
|
|
|
sendCompletionEvent(c, message.RequestID)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Continue polling for new events
|
|
|
|
|
|
logger.Debug(ctx, "Starting event update monitoring")
|
|
|
|
|
|
ticker := time.NewTicker(100 * time.Millisecond)
|
|
|
|
|
|
defer ticker.Stop()
|
|
|
|
|
|
|
|
|
|
|
|
for {
|
|
|
|
|
|
select {
|
|
|
|
|
|
case <-c.Request.Context().Done():
|
|
|
|
|
|
logger.Debug(ctx, "Client connection closed")
|
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
|
|
case <-ticker.C:
|
|
|
|
|
|
// Get new events from current offset
|
|
|
|
|
|
newEvents, newOffset, err := h.streamManager.GetEvents(ctx, sessionID, messageID, currentOffset)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
logger.Errorf(ctx, "Failed to get new events: %v", err)
|
fix(api): close the resource_urls=public gaps found in review
Follow-up on resource_urls=public. Review turned up one authorization gap plus a
set of correctness problems in the streaming path.
Authorization:
- Embed channels were documented as excluded, but nothing enforced it. The
delegating handlers hand the visitor's own gin context to the shared
handlers, so ?resource_urls=public — and a deployment-wide
RESOURCE_URL_MODE=public — reached anonymous traffic and produced
shareable, credential-free URLs that bypass the channel-scoped
/embed/:channel_id/files proxy. ensureEmbedSession now pins the request
context to handle mode, which covers every delegated endpoint including
future ones. The downgrade is silent so a client that forwards the
parameter keeps working.
- A knowledge-base-restricted API key is refused with 403. Such a key is
already denied /files because a raw storage path cannot be bound to its
allow-list, so handing it anonymous file URLs would reopen that hole from
the other side. The default handle mode stays available to it.
Streaming:
- Rewriter.ref holds its lock across resolution. Resolver implementations keep
an unsynchronised per-provider cache, so the previous unlocked window was a
real data race for any caller sharing a StreamRewriter between goroutines —
which its own doc comment invited. Serialising also collapses a concurrent
duplicate into one signature.
- Release the holdback buffer on every path that ends a stream while the
client is still connected: a user-requested stop, an error event, and
giving up on the event store. Only completion flushed before, so the tail
generated just before a stop was silently dropped.
- A released tail carries the metadata of the event it was cut from instead of
a bare event_id.
- The maxHeldBytes safety valve aligns to a UTF-8 boundary rather than cutting
a character in half, and an unclosed "
|
2025-11-08 16:02:31 +00:00
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Send new events
|
|
|
|
|
|
streamCompletedNow := false
|
|
|
|
|
|
for _, evt := range newEvents {
|
|
|
|
|
|
// Check for completion event
|
|
|
|
|
|
if evt.Type == "complete" {
|
|
|
|
|
|
streamCompletedNow = true
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-08-04 09:14:52 +00:00
|
|
|
|
emitStreamEvent(ctx, c, evt, message.RequestID, resourceRewriter)
|
2025-11-08 16:02:31 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Update offset
|
|
|
|
|
|
currentOffset = newOffset
|
|
|
|
|
|
|
|
|
|
|
|
// If stream completed, send final event and exit
|
|
|
|
|
|
if streamCompletedNow {
|
|
|
|
|
|
logger.Infof(ctx, "Stream completed, session ID: %s, message ID: %s", sessionID, messageID)
|
|
|
|
|
|
sendCompletionEvent(c, message.RequestID)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-16 08:40:13 +00:00
|
|
|
|
// StopSession godoc
|
|
|
|
|
|
// @Summary 停止生成
|
|
|
|
|
|
// @Description 停止当前正在进行的生成任务
|
|
|
|
|
|
// @Tags 问答
|
|
|
|
|
|
// @Accept json
|
|
|
|
|
|
// @Produce json
|
|
|
|
|
|
// @Param session_id path string true "会话ID"
|
|
|
|
|
|
// @Param request body StopSessionRequest true "停止请求"
|
|
|
|
|
|
// @Success 200 {object} map[string]interface{} "停止成功"
|
|
|
|
|
|
// @Failure 404 {object} errors.AppError "会话或消息不存在"
|
|
|
|
|
|
// @Security Bearer
|
2025-12-22 06:36:29 +00:00
|
|
|
|
// @Security ApiKeyAuth
|
2025-12-16 08:40:13 +00:00
|
|
|
|
// @Router /sessions/{session_id}/stop [post]
|
2025-11-08 16:02:31 +00:00
|
|
|
|
func (h *Handler) StopSession(c *gin.Context) {
|
|
|
|
|
|
ctx := logger.CloneContext(c.Request.Context())
|
2025-11-26 05:14:29 +00:00
|
|
|
|
sessionID := secutils.SanitizeForLog(c.Param("session_id"))
|
2025-11-08 16:02:31 +00:00
|
|
|
|
|
|
|
|
|
|
if sessionID == "" {
|
|
|
|
|
|
c.JSON(400, gin.H{"error": "Session ID is required"})
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Parse request body to get message_id
|
|
|
|
|
|
var req StopSessionRequest
|
|
|
|
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
|
|
|
|
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
|
|
|
|
|
"session_id": sessionID,
|
|
|
|
|
|
})
|
|
|
|
|
|
c.JSON(400, gin.H{"error": "message_id is required"})
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-11-26 05:14:29 +00:00
|
|
|
|
assistantMessageID := secutils.SanitizeForLog(req.MessageID)
|
2025-11-08 16:02:31 +00:00
|
|
|
|
logger.Infof(ctx, "Stop generation request for session: %s, message: %s", sessionID, assistantMessageID)
|
|
|
|
|
|
|
|
|
|
|
|
// Get tenant ID from context
|
|
|
|
|
|
tenantID, exists := c.Get(types.TenantIDContextKey.String())
|
|
|
|
|
|
if !exists {
|
|
|
|
|
|
logger.Error(ctx, "Failed to get tenant ID")
|
|
|
|
|
|
c.JSON(401, gin.H{"error": "Unauthorized"})
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
2025-11-25 08:30:54 +00:00
|
|
|
|
tenantIDUint := tenantID.(uint64)
|
2025-11-08 16:02:31 +00:00
|
|
|
|
|
|
|
|
|
|
// Verify message ownership and status
|
|
|
|
|
|
message, err := h.messageService.GetMessage(ctx, sessionID, assistantMessageID)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
|
|
|
|
|
"session_id": sessionID,
|
|
|
|
|
|
"message_id": assistantMessageID,
|
|
|
|
|
|
})
|
|
|
|
|
|
c.JSON(404, gin.H{"error": "Message not found"})
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Verify message belongs to this session (double check)
|
|
|
|
|
|
if message.SessionID != sessionID {
|
|
|
|
|
|
logger.Warnf(ctx, "Message %s does not belong to session %s", assistantMessageID, sessionID)
|
|
|
|
|
|
c.JSON(403, gin.H{"error": "Message does not belong to this session"})
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-07-20 11:27:25 +00:00
|
|
|
|
// Verify message belongs to the current tenant. Stopping generation mutates
|
|
|
|
|
|
// an in-flight run, so use the strict owner scope: a tenant admin may read an
|
|
|
|
|
|
// API-key session but must not be able to interrupt its (external) API calls.
|
|
|
|
|
|
session, err := h.sessionService.GetOwnedSession(ctx, sessionID)
|
2025-11-08 16:02:31 +00:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
|
|
|
|
|
"session_id": sessionID,
|
|
|
|
|
|
})
|
|
|
|
|
|
c.JSON(404, gin.H{"error": "Session not found"})
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if session.TenantID != tenantIDUint {
|
|
|
|
|
|
logger.Warnf(ctx, "Session %s does not belong to tenant %d", sessionID, tenantIDUint)
|
|
|
|
|
|
c.JSON(403, gin.H{"error": "Access denied"})
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Check if message is already completed (stopped)
|
|
|
|
|
|
if message.IsCompleted {
|
|
|
|
|
|
logger.Infof(ctx, "Message %s is already completed, no need to stop", assistantMessageID)
|
|
|
|
|
|
c.JSON(200, gin.H{
|
|
|
|
|
|
"success": true,
|
|
|
|
|
|
"message": "Message already completed",
|
|
|
|
|
|
})
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Write stop event to StreamManager for distributed support
|
|
|
|
|
|
stopEvent := interfaces.StreamEvent{
|
|
|
|
|
|
ID: fmt.Sprintf("stop-%d", time.Now().UnixNano()),
|
|
|
|
|
|
Type: types.ResponseType(event.EventStop),
|
|
|
|
|
|
Content: "",
|
|
|
|
|
|
Done: true,
|
|
|
|
|
|
Timestamp: time.Now(),
|
|
|
|
|
|
Data: map[string]interface{}{
|
|
|
|
|
|
"session_id": sessionID,
|
|
|
|
|
|
"message_id": assistantMessageID,
|
|
|
|
|
|
"reason": "user_requested",
|
|
|
|
|
|
},
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if err := h.streamManager.AppendEvent(ctx, sessionID, assistantMessageID, stopEvent); err != nil {
|
|
|
|
|
|
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
|
|
|
|
|
"session_id": sessionID,
|
|
|
|
|
|
"message_id": assistantMessageID,
|
|
|
|
|
|
})
|
|
|
|
|
|
c.JSON(500, gin.H{"error": "Failed to write stop event"})
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
logger.Infof(ctx, "Stop event written successfully for session: %s, message: %s", sessionID, assistantMessageID)
|
|
|
|
|
|
c.JSON(200, gin.H{
|
|
|
|
|
|
"success": true,
|
|
|
|
|
|
"message": "Generation stopped",
|
|
|
|
|
|
})
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// handleAgentEventsForSSE handles agent events for SSE streaming using an existing handler
|
|
|
|
|
|
// The handler is already subscribed to events and AgentQA is already running
|
|
|
|
|
|
// This function polls StreamManager and pushes events to SSE, allowing graceful handling of disconnections
|
2025-12-19 14:17:56 +00:00
|
|
|
|
// waitForTitle: if true, wait for title event after completion (for new sessions without title)
|
2025-11-08 16:02:31 +00:00
|
|
|
|
func (h *Handler) handleAgentEventsForSSE(
|
|
|
|
|
|
ctx context.Context,
|
|
|
|
|
|
c *gin.Context,
|
|
|
|
|
|
sessionID, assistantMessageID, requestID string,
|
|
|
|
|
|
eventBus *event.EventBus,
|
2025-12-19 14:17:56 +00:00
|
|
|
|
waitForTitle bool,
|
2026-08-04 09:14:52 +00:00
|
|
|
|
resourceRewriter *storageurl.StreamRewriter,
|
2025-11-08 16:02:31 +00:00
|
|
|
|
) {
|
|
|
|
|
|
ticker := time.NewTicker(100 * time.Millisecond)
|
|
|
|
|
|
defer ticker.Stop()
|
|
|
|
|
|
|
|
|
|
|
|
lastOffset := 0
|
|
|
|
|
|
log := logger.GetLogger(ctx)
|
|
|
|
|
|
|
|
|
|
|
|
log.Infof("Starting pull-based SSE streaming for session=%s, message=%s", sessionID, assistantMessageID)
|
|
|
|
|
|
|
|
|
|
|
|
for {
|
|
|
|
|
|
select {
|
|
|
|
|
|
case <-c.Request.Context().Done():
|
|
|
|
|
|
// Connection closed, exit gracefully without panic
|
2025-11-28 08:17:52 +00:00
|
|
|
|
log.Infof(
|
|
|
|
|
|
"Client disconnected, stopping SSE streaming for session=%s, message=%s",
|
|
|
|
|
|
sessionID,
|
|
|
|
|
|
assistantMessageID,
|
|
|
|
|
|
)
|
2025-11-08 16:02:31 +00:00
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
|
|
case <-ticker.C:
|
|
|
|
|
|
// Get new events from StreamManager using offset
|
|
|
|
|
|
events, newOffset, err := h.streamManager.GetEvents(ctx, sessionID, assistantMessageID, lastOffset)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
log.Warnf("Failed to get events from stream: %v", err)
|
|
|
|
|
|
continue
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Send any new events
|
|
|
|
|
|
streamCompleted := false
|
2025-12-19 14:17:56 +00:00
|
|
|
|
titleReceived := false
|
2025-11-08 16:02:31 +00:00
|
|
|
|
for _, evt := range events {
|
|
|
|
|
|
// Check for stop event
|
|
|
|
|
|
if evt.Type == types.ResponseType(event.EventStop) {
|
|
|
|
|
|
log.Infof("Detected stop event, triggering stop via EventBus for session=%s", sessionID)
|
|
|
|
|
|
|
|
|
|
|
|
// Emit stop event to the EventBus to trigger context cancellation
|
|
|
|
|
|
if eventBus != nil {
|
|
|
|
|
|
eventBus.Emit(ctx, event.Event{
|
|
|
|
|
|
Type: event.EventStop,
|
|
|
|
|
|
SessionID: sessionID,
|
|
|
|
|
|
Data: event.StopData{
|
|
|
|
|
|
SessionID: sessionID,
|
|
|
|
|
|
MessageID: assistantMessageID,
|
|
|
|
|
|
Reason: "user_requested",
|
|
|
|
|
|
},
|
|
|
|
|
|
})
|
|
|
|
|
|
}
|
|
|
|
|
|
|
fix(api): close the resource_urls=public gaps found in review
Follow-up on resource_urls=public. Review turned up one authorization gap plus a
set of correctness problems in the streaming path.
Authorization:
- Embed channels were documented as excluded, but nothing enforced it. The
delegating handlers hand the visitor's own gin context to the shared
handlers, so ?resource_urls=public — and a deployment-wide
RESOURCE_URL_MODE=public — reached anonymous traffic and produced
shareable, credential-free URLs that bypass the channel-scoped
/embed/:channel_id/files proxy. ensureEmbedSession now pins the request
context to handle mode, which covers every delegated endpoint including
future ones. The downgrade is silent so a client that forwards the
parameter keeps working.
- A knowledge-base-restricted API key is refused with 403. Such a key is
already denied /files because a raw storage path cannot be bound to its
allow-list, so handing it anonymous file URLs would reopen that hole from
the other side. The default handle mode stays available to it.
Streaming:
- Rewriter.ref holds its lock across resolution. Resolver implementations keep
an unsynchronised per-provider cache, so the previous unlocked window was a
real data race for any caller sharing a StreamRewriter between goroutines —
which its own doc comment invited. Serialising also collapses a concurrent
duplicate into one signature.
- Release the holdback buffer on every path that ends a stream while the
client is still connected: a user-requested stop, an error event, and
giving up on the event store. Only completion flushed before, so the tail
generated just before a stop was silently dropped.
- A released tail carries the metadata of the event it was cut from instead of
a bare event_id.
- The maxHeldBytes safety valve aligns to a UTF-8 boundary rather than cutting
a character in half, and an unclosed "
|
|
|
|
|
|
|
2025-11-08 16:02:31 +00:00
|
|
|
|
// Send stop notification to frontend
|
|
|
|
|
|
c.SSEvent("message", &types.StreamResponse{
|
|
|
|
|
|
ID: requestID,
|
|
|
|
|
|
ResponseType: "stop",
|
|
|
|
|
|
Content: "Generation stopped by user",
|
|
|
|
|
|
Done: true,
|
|
|
|
|
|
})
|
|
|
|
|
|
c.Writer.Flush()
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Check for completion event
|
|
|
|
|
|
if evt.Type == "complete" {
|
|
|
|
|
|
streamCompleted = true
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-19 14:17:56 +00:00
|
|
|
|
// Check for title event
|
|
|
|
|
|
if evt.Type == types.ResponseTypeSessionTitle {
|
|
|
|
|
|
titleReceived = true
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-08-04 09:30:52 +00:00
|
|
|
|
// Check if connection is still alive before writing. Build the
|
|
|
|
|
|
// payload only after this check: in public resource URL mode
|
|
|
|
|
|
// building consumes the chunk into the holdback buffer, so an
|
|
|
|
|
|
// early return here would drop it.
|
2025-11-08 16:02:31 +00:00
|
|
|
|
if c.Request.Context().Err() != nil {
|
|
|
|
|
|
log.Info("Connection closed during event sending, stopping")
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-08-04 09:30:52 +00:00
|
|
|
|
emitStreamEvent(ctx, c, evt, requestID, resourceRewriter)
|
2025-11-08 16:02:31 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Update offset
|
|
|
|
|
|
lastOffset = newOffset
|
|
|
|
|
|
|
2025-12-19 14:17:56 +00:00
|
|
|
|
// Check if stream is completed - wait for title event only if needed and not already received
|
2025-11-08 16:02:31 +00:00
|
|
|
|
if streamCompleted {
|
2025-12-19 14:17:56 +00:00
|
|
|
|
if waitForTitle && !titleReceived {
|
|
|
|
|
|
log.Infof("Stream completed for session=%s, message=%s, waiting for title event", sessionID, assistantMessageID)
|
|
|
|
|
|
// Wait up to 3 seconds for title event after completion
|
|
|
|
|
|
titleTimeout := time.After(3 * time.Second)
|
|
|
|
|
|
titleWaitLoop:
|
|
|
|
|
|
for {
|
|
|
|
|
|
select {
|
|
|
|
|
|
case <-titleTimeout:
|
|
|
|
|
|
log.Info("Title wait timeout, closing stream")
|
|
|
|
|
|
break titleWaitLoop
|
|
|
|
|
|
case <-c.Request.Context().Done():
|
|
|
|
|
|
log.Info("Connection closed while waiting for title")
|
|
|
|
|
|
return
|
|
|
|
|
|
default:
|
|
|
|
|
|
// Check for new events (title event)
|
|
|
|
|
|
events, newOff, err := h.streamManager.GetEvents(c.Request.Context(), sessionID, assistantMessageID, lastOffset)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
log.Warnf("Error getting events while waiting for title: %v", err)
|
|
|
|
|
|
break titleWaitLoop
|
|
|
|
|
|
}
|
|
|
|
|
|
if len(events) > 0 {
|
|
|
|
|
|
for _, evt := range events {
|
2026-08-04 09:14:52 +00:00
|
|
|
|
emitStreamEvent(ctx, c, evt, requestID, resourceRewriter)
|
2025-12-19 14:17:56 +00:00
|
|
|
|
// If we got the title, we can exit
|
|
|
|
|
|
if evt.Type == types.ResponseTypeSessionTitle {
|
|
|
|
|
|
log.Infof("Title event received: %s", evt.Content)
|
|
|
|
|
|
break titleWaitLoop
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
lastOffset = newOff
|
|
|
|
|
|
} else {
|
|
|
|
|
|
// No events, wait a bit before checking again
|
|
|
|
|
|
time.Sleep(100 * time.Millisecond)
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
} else {
|
|
|
|
|
|
log.Infof("Stream completed for session=%s, message=%s", sessionID, assistantMessageID)
|
|
|
|
|
|
}
|
2025-11-08 16:02:31 +00:00
|
|
|
|
sendCompletionEvent(c, requestID)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|