Files
multica/server/internal/handler/share_link.go
T
14c2e4e831 MUL-6243 feat(issue-status): board fetches by category; archive retires without migration (#7084)
* feat(issue-status): board fetches by category; archive retires without migration (MUL-6243)

Product decisions from the issue thread:

1. Board fetches by CATEGORY, not per status. PAGINATED_STATUSES becomes
   PAGINATED_CATEGORIES and the cache buckets by category, so the board's
   fan-out stays fixed at 7 parallel requests however many custom statuses a
   workspace defines — instead of one more request per status added. Adds
   status_category / status_categories filters to the issue list endpoints,
   backed by the existing issue_effective_status() SQL function.

3. Archiving retires a status from FUTURE use only. It no longer refuses while
   issues still carry it: those issues keep their status and keep resolving to
   their category's behavior (Effective ignores archived_at), while Resolve
   still rejects the status so nothing new can be assigned to it. The exclusive
   catalog lock stays — it is what makes "no NEW assignment after archive"
   exact rather than approximate.

Also lands the frontend catalog foundation: packages/core/issue-statuses with
useIssueStatuses(wsId) (React Query, keyed by wsId per the state rules) and a
pure buildIssueStatusCatalog for non-React callers, plus IssueStatusCategory as
a distinct type from the status key and status_category on issue payloads.

NOT included, and deliberately: widening IssueStatus to string. That change
forces every Record<IssueStatus, …> presentation lookup in packages/views to
resolve a key to its category first, and it is the first task of the follow-up
PR. Everything here is the groundwork that makes it mechanical.

Co-authored-by: multica-agent <[email protected]>

* fix(issue-status): restore the status index, make category authoritative, keep archived resolvable

Review round 1 on #7084 (MUL-6243):

1. Category filtering wrapped issue.status in issue_effective_status(), which
   makes the (workspace_id, status) index unusable — and the board switched to
   it unconditionally, so every workspace paid for it immediately. Categories
   are now expanded to concrete status keys (issuestatus.ExpandCategories) and
   filtered with an indexed status = ANY(...). Measured on a 100k-row table
   with the production index: seq scan cost 27013 -> index-only scan cost 6.07.
   A workspace with no custom statuses expands each category to exactly its own
   key, reproducing the pre-feature query. Archived keys are included, since
   issues left on them still belong in their category's column.

2. status_category was only filled for built-ins, so a custom-status issue
   arriving over the websocket was silently dropped by addIssueToBuckets and a
   cross-category update was skipped by the cache coordinator, drifting
   off-window totals permanently. List, grouped, get, create, update and batch
   responses now carry an authoritative category via a per-request Resolver
   (archived included), and the client invalidates instead of no-oping when a
   category is unresolvable.

3. The catalog was fetched without archived entries, so after archiving a
   status the issues still on it lost their name and colour and had their
   category guessed as todo — contradicting the decision that archiving leaves
   existing issues untouched. Resolution now includes archived entries;
   activeStatuses / inCategory expose only assignable ones to pickers.

Co-authored-by: multica-agent <[email protected]>

* fix(issue-status): category on every payload exit, one resolver per request, no same-category duplication

Review round 2 on #7084 (MUL-6243):

1. Category fill was incomplete and N+1. The create WEBSOCKET payload was
   unfilled — only the creator's HTTP response was, which is too late for the
   other tabs the event exists to serve. GetIssue, the open_only list, search,
   the duplicate-conflict response, the table rows, the GitHub PR update and
   the onboarding shim were also unfilled. Grouped and batch called the
   single-response helper per row, so each custom-status row hit the catalog
   separately.

   Every exit now goes through newStatusCategoryFiller, a request-scoped
   closure over ONE Resolver: built-in statuses still cost no query, and a page
   of custom-status rows costs one catalog read rather than one per row.

2. A status KEY change within one category duplicated the card and inflated the
   total. patchIssueInBuckets compared patch.status (a key) against loc.status
   (a bucket CATEGORY), so in_review -> a custom human_review took the
   cross-bucket path, then deleted from and re-inserted into the same bucket
   from a pre-delete snapshot. It now resolves the destination category first
   and compares category to category; same-category changes replace in place
   and leave the total alone.

   The destination category is resolved from the patch alone — the merged issue
   inherits the previous status_category, which would have kept a genuinely
   moved card in its old column. patchNeedsInvalidation lets the loaded branch
   of the cache coordinator invalidate instead of silently no-oping on a status
   it cannot resolve.

Also drops the unrelated share_link.sql.go churn from an sqlc version
difference, per the review nit.

The four cache cases were verified to fail against the previous logic (card
duplicated, total +1) before the fix was restored.

Co-authored-by: multica-agent <[email protected]>

* fix(issue-status): normalize status_category on every cache write; one filler per create

Review round 3 on #7084 (MUL-6243):

Must-fix — a cached entity kept the STALE status_category after a status
change. The server now sends a category on every issue, so a cached entity is
{status: "todo", status_category: "todo"}; an optimistic patch carries only
{status: "done"}, and a bare {...issue, ...patch} moved the card to the done
bucket while the entity still claimed todo. A single update self-heals from the
server response, but the batch API returns only {updated: n} and does not
refetch bucketed lists, so the inconsistency was permanent — and the next
off-window count then decremented the wrong bucket, recreating total drift.

normalizeStatusPatch now rewrites status_category to match status before any
cache write, applied at applyIssueChange's entry (covering the flat, table and
detail spreads), in patchIssueInBuckets, and in the children mutation. An
unresolvable custom key drops the inherited category rather than keeping it;
patchNeedsInvalidation still routes it to a refetch.

Test fixtures now carry status_category for built-ins, matching what the server
actually sends — without that the regression was invisible.

Non-blocking items also addressed:
- CreateIssue builds one filler and shares it between the broadcast payload and
  the HTTP response, so a custom-status create reads the catalog once.
- Background events via IssueToMap now resolve an authoritative category
  (IssueToMapWithCategory) for the task, issue and autopilot publishers. The
  channel router keeps plain IssueToMap and says why: it always creates with the
  built-in "todo", where key IS category.

The "one resolver serves a whole page" assertion was REMOVED rather than kept:
pg_stat counters lag, so a delta around one request passes even with a per-row
filler. Verified that directly before dropping it. The comment now states what
is and is not pinned instead of implying coverage that does not exist.

Co-authored-by: multica-agent <[email protected]>

* fix(issue-status): address review nits

- Normalize the single-update children optimistic patch too, matching the batch
  path. It self-healed on onSettled, but it broke the entity/bucket invariant
  for the duration of the request.
- Rename TestListEndpointsCarryStatusCategory: the old name claimed it covered
  "without per row queries", which the test explicitly does not assert.
- Drop the unrelated gofmt churn in empty_claim_cache.go.
- Add a background-event assertion: IssueToMap leaves a custom status
  uncategorized, IssueToMapWithCategory resolves it — the reason the publishers
  use the latter.

Co-authored-by: multica-agent <[email protected]>

---------

Co-authored-by: Bohan-J <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-08-18 03:00:21 +08:00

410 lines
13 KiB
Go

package handler
import (
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"log/slog"
"math"
"net/http"
"strings"
"time"
"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"
)
// expiresInMaxHours is the largest hour count that can be multiplied by
// time.Hour without overflowing a signed 64-bit time.Duration. Rejecting
// anything above it prevents expires_in from wrapping to a negative duration
// (which would make a freshly created link instantly expired).
const expiresInMaxHours = math.MaxInt64 / int64(time.Hour)
// ShareLinkResponse is the JSON shape returned for a workspace share link.
type ShareLinkResponse struct {
ID string `json:"id"`
WorkspaceID string `json:"workspace_id"`
Code string `json:"code"`
CreatedBy string `json:"created_by"`
Role string `json:"role"`
ExpiresAt *string `json:"expires_at,omitempty"`
MaxUses *int32 `json:"max_uses,omitempty"`
UseCount int32 `json:"use_count"`
IsActive bool `json:"is_active"`
CreatedAt string `json:"created_at"`
// Enriched
CreatorName string `json:"creator_name,omitempty"`
CreatorEmail string `json:"creator_email,omitempty"`
}
type CreateShareLinkRequest struct {
Role string `json:"role"`
ExpiresIn *int `json:"expires_in,omitempty"` // hours from now
MaxUses *int `json:"max_uses,omitempty"`
}
type JoinByShareLinkRequest struct {
Code string `json:"code"`
}
func generateShareCode() (string, error) {
b := make([]byte, 12)
if _, err := rand.Read(b); err != nil {
return "", err
}
return hex.EncodeToString(b), nil
}
// CreateShareLink — admin creates a shareable invite link.
// POST /api/workspaces/{id}/share-links
func (h *Handler) CreateShareLink(w http.ResponseWriter, r *http.Request) {
workspaceID := workspaceIDFromURL(r, "id")
requester, ok := h.workspaceMember(w, r, workspaceID)
if !ok {
return
}
var req CreateShareLinkRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
return
}
role := "member"
if req.Role != "" {
r := strings.ToLower(strings.TrimSpace(req.Role))
if r == "admin" {
role = "admin"
} else if r != "member" {
writeError(w, http.StatusBadRequest, "invalid role")
return
}
}
// Validate expiry and usage bounds instead of silently treating bad input
// as "no limit": zero/negative and overflow-range values are rejected
// outright. max_uses is stored as int32, and expires_in is multiplied by
// time.Hour into a time.Duration, so both need an explicit upper bound to
// avoid wrapping or overflow before conversion.
var expiresAt pgtype.Timestamptz
if req.ExpiresIn != nil {
if *req.ExpiresIn <= 0 || int64(*req.ExpiresIn) > expiresInMaxHours {
writeError(w, http.StatusBadRequest, fmt.Sprintf("expires_in must be between 1 and %d hours", expiresInMaxHours))
return
}
expiresAt = pgtype.Timestamptz{Time: time.Now().Add(time.Duration(*req.ExpiresIn) * time.Hour), Valid: true}
}
var maxUses pgtype.Int4
if req.MaxUses != nil {
if *req.MaxUses <= 0 || *req.MaxUses > math.MaxInt32 {
writeError(w, http.StatusBadRequest, "max_uses must be between 1 and 2147483647")
return
}
maxUses = pgtype.Int4{Int32: int32(*req.MaxUses), Valid: true}
}
// Rotating to a new link and deactivating the previous one must be atomic:
// deactivating outside the transaction (as before) could destroy the old
// working link if the insert fails, and ignoring deactivation errors could
// leave multiple active links. The partial unique index on
// (workspace_id) WHERE is_active also fails closed on concurrent creates.
tx, err := h.TxStarter.Begin(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to create share link")
return
}
defer tx.Rollback(r.Context())
qtx := h.Queries.WithTx(tx)
if err := qtx.DeactivateWorkspaceShareLinks(r.Context(), requester.WorkspaceID); err != nil {
slog.Warn("deactivate share links failed", append(logger.RequestAttrs(r), "error", err)...)
writeError(w, http.StatusInternalServerError, "failed to create share link")
return
}
code, err := generateShareCode()
if err != nil {
slog.Warn("generate share code failed", append(logger.RequestAttrs(r), "error", err)...)
writeError(w, http.StatusInternalServerError, "failed to create share link")
return
}
link, err := qtx.CreateShareLink(r.Context(), db.CreateShareLinkParams{
WorkspaceID: requester.WorkspaceID,
Code: code,
CreatedBy: requester.UserID,
Role: role,
ExpiresAt: expiresAt,
MaxUses: maxUses,
})
if err != nil {
if isUniqueViolation(err) {
writeError(w, http.StatusConflict, "a share link is already active for this workspace")
return
}
slog.Warn("create share link failed", append(logger.RequestAttrs(r), "error", err)...)
writeError(w, http.StatusInternalServerError, "failed to create share link")
return
}
if err := tx.Commit(r.Context()); err != nil {
slog.Warn("commit share link failed", append(logger.RequestAttrs(r), "error", err)...)
writeError(w, http.StatusInternalServerError, "failed to create share link")
return
}
slog.Info("share link created", append(logger.RequestAttrs(r), "share_link_id", uuidToString(link.ID), "workspace_id", workspaceID)...)
resp := shareLinkToResponse(link)
writeJSON(w, http.StatusCreated, resp)
}
// ListShareLinks — list active share links for a workspace (admin view).
// GET /api/workspaces/{id}/share-links
func (h *Handler) ListShareLinks(w http.ResponseWriter, r *http.Request) {
workspaceID := workspaceIDFromURL(r, "id")
workspaceUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
if !ok {
return
}
rows, err := h.Queries.ListShareLinksByWorkspace(r.Context(), workspaceUUID)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to list share links")
return
}
resp := make([]ShareLinkResponse, len(rows))
for i, row := range rows {
resp[i] = shareLinkListToResponse(row)
}
if resp == nil {
resp = []ShareLinkResponse{}
}
writeJSON(w, http.StatusOK, resp)
}
// RevokeShareLink — admin revokes a share link.
// DELETE /api/workspaces/{id}/share-links/{linkId}
func (h *Handler) RevokeShareLink(w http.ResponseWriter, r *http.Request) {
workspaceID := workspaceIDFromURL(r, "id")
linkID := chi.URLParam(r, "linkId")
workspaceUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
if !ok {
return
}
linkUUID, ok := parseUUIDOrBadRequest(w, linkID, "link id")
if !ok {
return
}
if err := h.Queries.RevokeShareLink(r.Context(), db.RevokeShareLinkParams{
ID: linkUUID,
WorkspaceID: workspaceUUID,
}); err != nil {
writeError(w, http.StatusInternalServerError, "failed to revoke share link")
return
}
slog.Info("share link revoked", "share_link_id", linkID, "workspace_id", workspaceID)
w.WriteHeader(http.StatusNoContent)
}
// ShareLinkInfoResponse is the public, pre-join preview of a share link:
// only what a visitor needs to decide whether to join — the workspace name,
// its slug, the inviting user's display name, and the role the link grants.
// It deliberately excludes internal IDs (workspace_id), the invite code, and
// the inviter's email address.
type ShareLinkInfoResponse struct {
WorkspaceName string `json:"workspace_name"`
WorkspaceSlug string `json:"workspace_slug"`
CreatorName string `json:"creator_name,omitempty"`
Role string `json:"role"`
}
// GetShareLinkInfo — public preview of a workspace share link. No auth is
// required so a not-yet-logged-in visitor can see what they're joining before
// signing in. Only the workspace name/slug and inviter are exposed.
// GET /api/share-links/{code}
func (h *Handler) GetShareLinkInfo(w http.ResponseWriter, r *http.Request) {
code := chi.URLParam(r, "code")
code = strings.TrimSpace(code)
if code == "" {
writeError(w, http.StatusBadRequest, "code is required")
return
}
row, err := h.Queries.GetShareLinkInfoByCode(r.Context(), code)
if err != nil {
writeError(w, http.StatusNotFound, "share link not found or expired")
return
}
writeJSON(w, http.StatusOK, ShareLinkInfoResponse{
WorkspaceName: row.WorkspaceName,
WorkspaceSlug: row.WorkspaceSlug,
CreatorName: row.CreatorName,
Role: row.Role,
})
}
// JoinByShareLink — authenticated user joins a workspace via a share link.
// POST /api/share-links/join
func (h *Handler) JoinByShareLink(w http.ResponseWriter, r *http.Request) {
userID, ok := requireUserID(w, r)
if !ok {
return
}
var req JoinByShareLinkRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
return
}
code := strings.TrimSpace(req.Code)
if code == "" {
writeError(w, http.StatusBadRequest, "code is required")
return
}
user, err := h.Queries.GetUser(r.Context(), parseUUID(userID))
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to load user")
return
}
// Open the transaction first, then atomically claim the link. The claim is
// a conditional UPDATE that revalidates active/not-expired/below-max_uses
// and increments use_count in one statement, so concurrent joins cannot
// exceed max_uses and a join cannot race past a revocation/expiry.
tx, err := h.TxStarter.Begin(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to join workspace")
return
}
defer tx.Rollback(r.Context())
qtx := h.Queries.WithTx(tx)
link, err := qtx.ClaimShareLinkByCode(r.Context(), code)
if err != nil {
writeError(w, http.StatusNotFound, "share link not found or expired")
return
}
// Check if already a member — if so, roll back the claimed use count.
_, memberErr := qtx.GetMemberByUserAndWorkspace(r.Context(), db.GetMemberByUserAndWorkspaceParams{
UserID: user.ID,
WorkspaceID: link.WorkspaceID,
})
if memberErr == nil {
writeError(w, http.StatusConflict, "you are already a member of this workspace")
return
}
member, err := qtx.CreateMember(r.Context(), db.CreateMemberParams{
WorkspaceID: link.WorkspaceID,
UserID: user.ID,
Role: link.Role,
})
if err != nil {
if isUniqueViolation(err) {
writeError(w, http.StatusConflict, "you are already a member of this workspace")
return
}
writeError(w, http.StatusInternalServerError, "failed to create membership")
return
}
// Mark onboarded. A failure here must roll the whole join back, otherwise a
// first-time user could become a member while still blocked by onboarding.
if _, err := qtx.MarkUserOnboarded(r.Context(), user.ID); err != nil {
writeError(w, http.StatusInternalServerError, "failed to finalize onboarding")
return
}
if err := tx.Commit(r.Context()); err != nil {
writeError(w, http.StatusInternalServerError, "failed to join workspace")
return
}
wsID := uuidToString(link.WorkspaceID)
slog.Info("user joined via share link", "user_id", userID, "workspace_id", wsID)
ws, err := h.Queries.GetWorkspace(r.Context(), link.WorkspaceID)
wsSlug := ""
if err == nil {
wsSlug = ws.Slug
}
memberResp := h.memberWithUserResponse(member, user)
h.publish(protocol.EventMemberAdded, wsID, "member", userID, map[string]any{
"member": memberResp,
})
h.notifyDaemonWorkspacesChanged(userID)
writeJSON(w, http.StatusOK, map[string]any{
"member": memberResp,
"workspace_id": wsID,
"workspace_slug": wsSlug,
})
}
func shareLinkToResponse(link db.WorkspaceShareLink) ShareLinkResponse {
var expiresAt *string
if link.ExpiresAt.Valid {
s := timestampToString(link.ExpiresAt)
expiresAt = &s
}
var maxUses *int32
if link.MaxUses.Valid {
maxUses = &link.MaxUses.Int32
}
return ShareLinkResponse{
ID: uuidToString(link.ID),
WorkspaceID: uuidToString(link.WorkspaceID),
Code: link.Code,
CreatedBy: uuidToString(link.CreatedBy),
Role: link.Role,
ExpiresAt: expiresAt,
MaxUses: maxUses,
UseCount: link.UseCount,
IsActive: link.IsActive,
CreatedAt: timestampToString(link.CreatedAt),
}
}
func shareLinkListToResponse(row db.ListShareLinksByWorkspaceRow) ShareLinkResponse {
var expiresAt *string
if row.ExpiresAt.Valid {
s := timestampToString(row.ExpiresAt)
expiresAt = &s
}
var maxUses *int32
if row.MaxUses.Valid {
maxUses = &row.MaxUses.Int32
}
return ShareLinkResponse{
ID: uuidToString(row.ID),
WorkspaceID: uuidToString(row.WorkspaceID),
Code: row.Code,
CreatedBy: uuidToString(row.CreatedBy),
Role: row.Role,
ExpiresAt: expiresAt,
MaxUses: maxUses,
UseCount: row.UseCount,
IsActive: row.IsActive,
CreatedAt: timestampToString(row.CreatedAt),
CreatorName: row.CreatorName,
CreatorEmail: row.CreatorEmail,
}
}