WeKnora/internal/handler/session/artifact_delete.go

136 lines
5.2 KiB
Go
Raw Normal View History

feat(artifacts): let users delete generated files (#3447) * feat(artifacts): let users delete generated files 技能生成的文件此前只能列出、预览和下载,没有任何删除入口,后端 handler/service/repository 三层都没有实现。DeleteSession 里那句注释 ("a dedicated GC job or explicit hard-delete API is the right place to reclaim storage") 留的就是这个位置。 Tombstone, not a row delete. message_artifacts 新增 deleted_at,删除只 打标记不删行。position 是下载接口寻址用的下标(msg.Artifacts[index]), 物理删掉中间一行会让它后面的文件整体前移,已有链接下到错的文件;而 ArtifactCollector 的去重集就是从这张表读的,行没了之后沙箱里 mtime 未变 的同名文件下一轮就会被重新采集回来,删了又出现。墓碑同时挡住这两条。 loadArtifactsByMessage 因此刻意保留墓碑,展示侧用 MessageArtifacts.Live 过滤;NewMessageArtifactRecords 带上 DeletedAt,任何一次消息重写都能把 墓碑原样写回去。 Bytes. 字节是真回收的,走 catalog.Release 引用计数:一份文件可能同时被 知识库条目和后续回答持有,只有所有持有者都放手才 DeleteFile。删多个版本 时同一个对象可能来自多条消息,每条消息的绑定都要释放,字节只删一次。 回收发生在打标记之后,且只针对本次调用真正认领到的行——并发的第二次删除 认领不到任何行,也就不会去动别人正在回收的对象。释放失败一律保留字节: 留个孤儿 blob 以后还能靠墓碑上的 url 回收,删错了则是别人的文档里的图片 凭空消失。 Scope. 会话内面板每个版本单独一行,删的就是点的那一版;产物库一行代表 一个文件(带版本数),默认连同该文件在这个会话里的所有版本一起删,否则 删完这一行还在、只是显示上一版。权限比下载严一档:下载认共享智能体的 只读访问,删除只认会话归属人。 Inline references. 正文里的 resource:// 引用渲染成置灰加删除线的卡片, 不可点击,和「模型引用了不存在的文件」的 --pending 态区分开。图片类产物 也降级成卡片:走 renderImage 只会拉取失败,留下一张永远加载不出来的图。 墓碑必须留在传给渲染器的产物列表里——句柄形式与知识库图片同形,过滤掉 之后句柄对不上本条回答,会被当成外部受保护图片去拉一个已经不存在的 blob,结果是裂图。组件里因此拆出 liveArtifacts 只给计数和文件列表用。 Also: 产物库是 offset 分页的无限列表,删一行会让后续页整体前移漏掉一条, 改成按已显示行数取下一页并按 key 去重;access.ResolveMessageArtifact 与 MessageReferencesFile 不再让墓碑授权访问;SessionArtifacts 过滤墓碑, 避免新回答把引用绑到已删文件上;版本澄清文案不再把已删版本算进版本数。 docs/swagger.* 未重新生成:仓库里那份已经落后若干功能,重生成会带进约 1000 行无关漂移,另开 PR 同步。 * fix(artifacts): close the delete holes found in review Regeneration. loadKnownSet 把墓碑的 ContentHash 也放进了去重集,于是 knownSameContent 会把「删除后技能重新生成、字节恰好相同」当成 fork checkout 那种 restore:不上传、不挂回本轮回答,文件再也回不来。墓碑现在 只登记 (path, mtime),不进 hash 也不进 byPath —— 前者才是「沙箱文件没动 过就别复活」需要的键,后者是「同内容恢复」的短路,两件事不该共用。 RecordRestoredArtifactMtime 也不再改墓碑:它的 mtime 就是那把锁。 Message file proxy. /sessions/:id/messages/:message_id/files 走 MessageReferencesFile,而正文检查在最前面且无条件为真。删除不会重写回答, resource:// 句柄还留在正文里,于是这条代理会继续把已删文件交出去——包括 交给共享智能体的只读访客,也包括「字节因为知识库还持有而没被回收」的情形。 现在先看 artifacts:命中本条消息的墓碑直接 false,命中 live 直接 true, 其余(知识库图、附件)才回落到正文。同一文件挂在多个位置时只要还有一个 live 就仍然可取。 Cross-session bytes. CreateForked 复制产物行时连同存储 URL 一起复制,但 不会给副本重新 Bind,所以 catalog 的引用计数看不到分叉。在父会话里删除会 把分叉还在用的字节删掉。无 catalog 部署、以及存的是裸 provider 路径的行, 同样不在计数覆盖内。回收前新增一道 CountLiveArtifactsByURL:只要还有任何 未删除的行指向同一对象就保留字节,查不出来也保留。配套加了 url 的部分索引。 Atomicity. SoftDeleteSessionArtifacts 原来逐条 UPDATE 不带事务,删多版本 时中途失败会留下「一部分已隐藏、字节没回收、接口 500、用户重试 404」。 现在整批放进一个事务。writeMessageArtifacts 是整表替换,拿着删除前快照的 并发写会让墓碑复活而字节已在回收,现在按 position 把已存在的 deleted_at 合并回去——删除是唯一不允许被过期写覆盖的属性。 all_versions 两个路由改用同一个解析器(strconv.ParseBool),此前一个是 == "true"、另一个是 != "false",显式传 1/TRUE 在两边语义不同;缺省值仍 按路由区分。 测试:收集器三条(未动不复活 / 重新生成要回来 / live 的同内容恢复仍短路)、 access 三条(正文不能复活已删授权、多副本只要有 live 就可取、非产物引用 仍走正文)、service 七条(归属人校验、他人会话拒绝、并发认领为空、live 行仍在则保留字节、guard 失败保留字节、多版本按对象归并 owner、无 source_path 不扫全会话)、repository 三条(墓碑抗过期写、事务回滚、跨会话 URL 计数)、handler 一条(两个路由的 all_versions 解析矩阵)。其中 「重新生成要回来」在改回旧实现时确认会失败。 client/ 没有 artifacts 相关 API(只有一个 SSE 事件类型常量),无需同步。
2026-09-20 05:01:46 +00:00
package session
import (
stderrors "errors"
"net/http"
"strconv"
"strings"
"github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
secutils "github.com/Tencent/WeKnora/internal/utils"
"github.com/gin-gonic/gin"
)
// DeleteMessageArtifact godoc
// @Summary 删除会话中的产物文件
// @Description 删除某条 assistant 消息生成的单个文件;all_versions=true 时连同本会话中该文件的所有历史版本一并删除
// @Tags 会话
// @Produce json
// @Param session_id path string true "会话ID"
// @Param message_id path string true "消息ID"
// @Param index path int true "产物在消息中的位置"
// @Param all_versions query bool false "是否删除该文件的所有版本"
// @Success 200 {object} map[string]interface{}
// @Failure 404 {object} errors.AppError
// @Security Bearer
// @Router /sessions/{session_id}/messages/{message_id}/artifacts/{index} [delete]
//
// Addressed by the same (message, index) coordinates as the download endpoint,
// so a client deletes exactly the row it was showing. The in-chat panel lists
// every version separately and omits all_versions; the artifact library folds
// versions into one entry and sets it.
func (h *Handler) DeleteMessageArtifact(c *gin.Context) {
sessionID := secutils.SanitizeForLog(paramSessionID(c))
messageID := secutils.SanitizeForLog(c.Param("message_id"))
index, err := strconv.Atoi(c.Param("index"))
if err != nil || index < 0 {
_ = c.Error(errors.NewBadRequestError("invalid artifact index"))
return
}
h.deleteArtifact(c, &types.ArtifactDeleteRequest{
SessionID: sessionID,
MessageID: messageID,
Index: index,
AllVersions: artifactAllVersions(c, false),
})
}
// DeleteLibraryArtifact godoc
// @Summary 删除产物库中的文件
// @Description 删除产物库中的一个文件。产物库一行代表一个文件的最新版本,默认连同该文件在本会话中的所有历史版本一并删除
// @Tags 会话
// @Produce json
// @Param session_id query string true "会话ID"
// @Param message_id query string true "消息ID"
// @Param index query int true "产物在消息中的位置"
// @Param all_versions query bool false "是否删除所有版本,默认 true"
// @Success 200 {object} map[string]interface{}
// @Failure 404 {object} errors.AppError
// @Security Bearer
// @Router /artifacts [delete]
//
// Versions default to being deleted together here: the library row IS the file,
// with a version count rather than a row per regeneration, so deleting one
// version would leave the entry in place showing the previous one.
func (h *Handler) DeleteLibraryArtifact(c *gin.Context) {
index, err := strconv.Atoi(c.Query("index"))
if err != nil || index < 0 {
_ = c.Error(errors.NewBadRequestError("invalid artifact index"))
return
}
h.deleteArtifact(c, &types.ArtifactDeleteRequest{
SessionID: secutils.SanitizeForLog(c.Query("session_id")),
MessageID: secutils.SanitizeForLog(c.Query("message_id")),
Index: index,
AllVersions: artifactAllVersions(c, true),
})
}
// artifactAllVersions reads the all_versions flag. The two routes differ only
// in what an absent flag means, so they share one parser: an explicit value is
// read the same way on both, and "1"/"TRUE"/"yes" cannot mean one thing here
// and another there.
func artifactAllVersions(c *gin.Context, whenAbsent bool) bool {
raw := strings.TrimSpace(c.Query("all_versions"))
if raw == "" {
return whenAbsent
}
parsed, err := strconv.ParseBool(raw)
if err != nil {
return whenAbsent
}
return parsed
}
// deleteArtifact runs the tombstone-then-reclaim sequence both delete routes
// share. The order matters: the rows are marked first, and only the rows this
// call actually claimed have their bytes reclaimed, so two concurrent deletes
// cannot both try to remove the same object.
func (h *Handler) deleteArtifact(c *gin.Context, req *types.ArtifactDeleteRequest) {
ctx := c.Request.Context()
result, err := h.messageService.DeleteSessionArtifact(ctx, req)
if err != nil {
// A session the caller does not own reads as absent, matching the rest
// of the session routes.
if stderrors.Is(err, errors.ErrSessionNotFound) {
_ = c.Error(errors.NewNotFoundError(err.Error()))
return
}
var appErr *errors.AppError
if stderrors.As(err, &appErr) {
_ = c.Error(appErr)
return
}
logger.Errorf(ctx, "delete artifact failed: session=%s message=%s idx=%d err=%v",
req.SessionID, req.MessageID, req.Index, err)
_ = c.Error(errors.NewInternalServerError(err.Error()))
return
}
// The rows are gone from every listing at this point. Reclaiming the bytes
// is best-effort cleanup, not part of the user-visible outcome, so its
// failures are logged rather than turned into a failed delete.
h.reclaimArtifactBlobs(ctx, types.MustTenantIDFromContext(ctx), result.Reclaim)
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
"file_name": result.FileName,
"deleted": result.Deleted,
},
})
}