Files
multica/server/internal/handler/reaction.go
Naiyuan Qing f0f3cb5c3a fix(server): resolve X-Workspace-Slug in middleware-less handlers (#1165)
Problem
-------
The v2 workspace URL refactor (#1141) switched the frontend from sending
X-Workspace-ID (UUID) to X-Workspace-Slug. The workspace middleware was
updated to accept the slug and translate it via GetWorkspaceBySlug.

But the handler package maintained a PARALLEL resolver
(`resolveWorkspaceID` in handler.go) used by endpoints that sit outside
the workspace middleware — and that resolver was never updated. It only
checked context / ?workspace_id / X-Workspace-ID, never the slug.

/api/upload-file is the one production route that hit the broken path:
it's user-scoped (not behind workspace middleware) because it also
serves avatar uploads (no workspace). Post-refactor requests from the
frontend arrived with only X-Workspace-Slug; the handler resolver
returned "", the code fell into the "no workspace context" branch, and
every file upload since v2 landed in S3 with no corresponding DB
attachment row — files orphaned, invisible to the UI.

Root cause is structural: two resolvers doing the same job, written
independently, diverged silently when one was updated.

Fix
---
Collapse to a single shared helper. middleware.ResolveWorkspaceIDFromRequest
is the new canonical resolver; both the middleware's internal
`resolveWorkspaceUUID` (for middleware gating) and the handler-side
`(h *Handler).resolveWorkspaceID` (promoted from a package function)
now delegate to it. Priority order matches what the middleware has had
since v2: context > X-Workspace-Slug header > ?workspace_slug query >
X-Workspace-ID header > ?workspace_id query.

Impact analysis
---------------
47 call sites of the old `resolveWorkspaceID(r)` are renamed to
`h.resolveWorkspaceID(r)`. 46 of them sit behind workspace middleware,
so they hit the context fast path and see zero behavior change. The
one caller that actually gains capability is UploadFile — which now
correctly recognizes slug requests and creates DB attachment rows.

Tests
-----
- New table-driven unit test for ResolveWorkspaceIDFromRequest covers
  all priority levels and the unknown-slug fallback.
- Regression tests for UploadFile: once with X-Workspace-Slug only
  (the broken path), once with X-Workspace-ID only (legacy CLI/daemon
  compat path). Both assert that a DB attachment row is created.
- Full Go test suite passes; typecheck + pnpm test unaffected.

Plan
----
See docs/plans/2026-04-16-unify-workspace-identity-resolver.md for the
full first-principles writeup.

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 18:01:56 +08:00

171 lines
4.8 KiB
Go

package handler
import (
"encoding/json"
"log/slog"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/logger"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
)
type ReactionResponse struct {
ID string `json:"id"`
CommentID string `json:"comment_id"`
ActorType string `json:"actor_type"`
ActorID string `json:"actor_id"`
Emoji string `json:"emoji"`
CreatedAt string `json:"created_at"`
}
func reactionToResponse(r db.CommentReaction) ReactionResponse {
return ReactionResponse{
ID: uuidToString(r.ID),
CommentID: uuidToString(r.CommentID),
ActorType: r.ActorType,
ActorID: uuidToString(r.ActorID),
Emoji: r.Emoji,
CreatedAt: timestampToString(r.CreatedAt),
}
}
func (h *Handler) AddReaction(w http.ResponseWriter, r *http.Request) {
commentId := chi.URLParam(r, "commentId")
userID, ok := requireUserID(w, r)
if !ok {
return
}
workspaceID := h.resolveWorkspaceID(r)
comment, err := h.Queries.GetCommentInWorkspace(r.Context(), db.GetCommentInWorkspaceParams{
ID: parseUUID(commentId),
WorkspaceID: parseUUID(workspaceID),
})
if err != nil {
writeError(w, http.StatusNotFound, "comment not found")
return
}
var req struct {
Emoji string `json:"emoji"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
return
}
if req.Emoji == "" {
writeError(w, http.StatusBadRequest, "emoji is required")
return
}
actorType, actorID := h.resolveActor(r, userID, workspaceID)
reaction, err := h.Queries.AddReaction(r.Context(), db.AddReactionParams{
CommentID: comment.ID,
WorkspaceID: parseUUID(workspaceID),
ActorType: actorType,
ActorID: parseUUID(actorID),
Emoji: req.Emoji,
})
if err != nil {
slog.Warn("add reaction failed", append(logger.RequestAttrs(r), "error", err, "comment_id", commentId)...)
writeError(w, http.StatusInternalServerError, "failed to add reaction")
return
}
resp := reactionToResponse(reaction)
// Look up issue title for inbox notifications.
issueID := uuidToString(comment.IssueID)
var issueTitle, issueStatus string
if issue, err := h.Queries.GetIssue(r.Context(), comment.IssueID); err == nil {
issueTitle = issue.Title
issueStatus = issue.Status
}
h.publish(protocol.EventReactionAdded, workspaceID, actorType, actorID, map[string]any{
"reaction": resp,
"issue_id": issueID,
"issue_title": issueTitle,
"issue_status": issueStatus,
"comment_id": uuidToString(comment.ID),
"comment_author_type": comment.AuthorType,
"comment_author_id": uuidToString(comment.AuthorID),
})
writeJSON(w, http.StatusCreated, resp)
}
func (h *Handler) RemoveReaction(w http.ResponseWriter, r *http.Request) {
commentId := chi.URLParam(r, "commentId")
userID, ok := requireUserID(w, r)
if !ok {
return
}
workspaceID := h.resolveWorkspaceID(r)
comment, err := h.Queries.GetCommentInWorkspace(r.Context(), db.GetCommentInWorkspaceParams{
ID: parseUUID(commentId),
WorkspaceID: parseUUID(workspaceID),
})
if err != nil {
writeError(w, http.StatusNotFound, "comment not found")
return
}
var req struct {
Emoji string `json:"emoji"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
return
}
if req.Emoji == "" {
writeError(w, http.StatusBadRequest, "emoji is required")
return
}
actorType, actorID := h.resolveActor(r, userID, workspaceID)
if err := h.Queries.RemoveReaction(r.Context(), db.RemoveReactionParams{
CommentID: comment.ID,
ActorType: actorType,
ActorID: parseUUID(actorID),
Emoji: req.Emoji,
}); err != nil {
slog.Warn("remove reaction failed", append(logger.RequestAttrs(r), "error", err, "comment_id", commentId)...)
writeError(w, http.StatusInternalServerError, "failed to remove reaction")
return
}
h.publish(protocol.EventReactionRemoved, workspaceID, actorType, actorID, map[string]any{
"comment_id": commentId,
"issue_id": uuidToString(comment.IssueID),
"emoji": req.Emoji,
"actor_type": actorType,
"actor_id": actorID,
})
w.WriteHeader(http.StatusNoContent)
}
// groupReactions fetches reactions for the given comment IDs and groups them by comment_id.
func (h *Handler) groupReactions(r *http.Request, commentIDs []pgtype.UUID) map[string][]ReactionResponse {
if len(commentIDs) == 0 {
return nil
}
reactions, err := h.Queries.ListReactionsByCommentIDs(r.Context(), commentIDs)
if err != nil {
return nil
}
grouped := make(map[string][]ReactionResponse, len(commentIDs))
for _, rx := range reactions {
cid := uuidToString(rx.CommentID)
grouped[cid] = append(grouped[cid], reactionToResponse(rx))
}
return grouped
}