Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go
16.8 KB
Raw Blame
package handler

import (
	"context"
	"encoding/json"
	"errors"
	"log/slog"
	"net/http"

	"github.com/go-chi/chi/v5"
	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgtype"
	"github.com/multica-ai/multica/server/internal/inbox"
	db "github.com/multica-ai/multica/server/pkg/db/generated"
	"github.com/multica-ai/multica/server/pkg/protocol"
)

// SubscriberResponse is the JSON shape returned for each issue subscriber.
type SubscriberResponse struct {
	IssueID   string `json:"issue_id"`
	UserType  string `json:"user_type"`
	UserID    string `json:"user_id"`
	Reason    string `json:"reason"`
	CreatedAt string `json:"created_at"`
	// ProjectCovered marks a direct row whose member also subscribes to the
	// issue's project. Delivery already accounts for it; clients that predate
	// Delivery still read it.
	ProjectCovered bool `json:"project_covered,omitempty"`
	// Delivery is how much of this issue the member actually receives, as the
	// notification fanout decides it. Absent on agent rows, which get no inbox.
	Delivery inbox.Delivery `json:"delivery,omitempty"`
}

func subscriberToResponse(s db.IssueSubscriber) SubscriberResponse {
	return SubscriberResponse{
		IssueID:   uuidToString(s.IssueID),
		UserType:  s.UserType,
		UserID:    uuidToString(s.UserID),
		Reason:    s.Reason,
		CreatedAt: timestampToString(s.CreatedAt),
	}
}

// ListIssueSubscribers returns all subscribers for an issue.
func (h *Handler) ListIssueSubscribers(w http.ResponseWriter, r *http.Request) {
	issueID := chi.URLParam(r, "id")
	issue, ok := h.loadIssueForUser(w, r, issueID)
	if !ok {
		return
	}

	subscribers, err := h.Queries.ListIssueSubscribers(r.Context(), issue.ID)
	if err != nil {
		writeError(w, http.StatusInternalServerError, "failed to list subscribers")
		return
	}

	// Project subscribers have no row here but are notified all the same, so
	// they are part of the issue's effective list. A direct row wins: it
	// carries the reason the member is involved in this issue specifically.
	projectSubscribers, err := h.Queries.ListProjectSubscribersForIssue(r.Context(), issue.ID)
	if err != nil {
		writeError(w, http.StatusInternalServerError, "failed to list subscribers")
		return
	}

	projectCovered := make(map[string]bool, len(projectSubscribers))
	for _, ps := range projectSubscribers {
		projectCovered[uuidToString(ps.UserID)] = true
	}

	var memberIDs []pgtype.UUID
	for _, s := range subscribers {
		if s.UserType == "member" {
			memberIDs = append(memberIDs, s.UserID)
		}
	}
	prefs := inbox.LoadPreferences(r.Context(), h.Queries, issue.WorkspaceID, memberIDs)
	ownerLoaded := false
	var owner inbox.IssueOwner
	var ownerErr error
	// Fails open like the fanout: an unreadable owner delivers every event.
	isSomeoneElses := func(userID string) bool {
		if !ownerLoaded {
			ownerLoaded = true
			owner, ownerErr = inbox.LoadIssueOwner(r.Context(), h.Queries, issue)
			if ownerErr != nil {
				slog.Warn("resolve issue owner for subscriber delivery", "issue_id", issueID, "error", ownerErr)
			}
		}
		return ownerErr == nil && owner.IsSomeoneElses(userID)
	}

	resp := make([]SubscriberResponse, 0, len(subscribers)+len(projectSubscribers))
	direct := make(map[string]bool, len(subscribers))
	for _, s := range subscribers {
		row := subscriberToResponse(s)
		if s.UserType == "member" {
			direct[row.UserID] = true
			row.ProjectCovered = projectCovered[row.UserID]
			// The project fanout delivers every event to a project watcher on
			// top of whatever the direct row narrows to.
			if row.ProjectCovered {
				row.Delivery = inbox.DeliveryAll
			} else {
				userID := row.UserID
				row.Delivery = inbox.SubscriptionDelivery(s.Reason, prefs[userID],
					func() bool { return isSomeoneElses(userID) })
			}
		}
		resp = append(resp, row)
	}
	for _, ps := range projectSubscribers {
		userID := uuidToString(ps.UserID)
		if direct[userID] {
			continue
		}
		resp = append(resp, SubscriberResponse{
			IssueID:   uuidToString(issue.ID),
			UserType:  "member",
			UserID:    userID,
			Reason:    subscriberReasonProject,
			CreatedAt: timestampToString(ps.CreatedAt),
			Delivery:  inbox.DeliveryAll,
		})
	}

	writeJSON(w, http.StatusOK, resp)
}

// subscriberReasonProject marks a subscription inherited from the issue's
// project. It is never stored on issue_subscriber; leaving the issue writes an
// opt-out tombstone instead (RemoveIssueSubscriber).
const subscriberReasonProject = "project"

// ListSubscribedIssueIDs returns the ids of every issue in the workspace the
// caller subscribes to, so clients can evaluate the "subscribed" relation on
// rows they filter themselves.
func (h *Handler) ListSubscribedIssueIDs(w http.ResponseWriter, r *http.Request) {
	userID, ok := requireUserID(w, r)
	if !ok {
		return
	}
	workspaceID := ctxWorkspaceID(r.Context())
	wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
	if !ok {
		return
	}
	hidden, ok := h.requestHiddenProjects(w, r, workspaceID)
	if !ok {
		return
	}
	ids, err := h.Queries.ListSubscribedIssueIDs(r.Context(), db.ListSubscribedIssueIDsParams{
		WorkspaceID:      wsUUID,
		UserID:           parseUUID(userID),
		HiddenProjectIds: hidden.Param(),
	})
	if err != nil {
		writeError(w, http.StatusInternalServerError, "failed to list subscribed issues")
		return
	}
	issueIDs := make([]string, len(ids))
	for i, id := range ids {
		issueIDs[i] = uuidToString(id)
	}
	writeJSON(w, http.StatusOK, map[string][]string{"issue_ids": issueIDs})
}

// SubscribeToIssue subscribes a user to an issue with reason "manual".
// If request body contains user_id, subscribes that user; otherwise subscribes the caller.
func (h *Handler) SubscribeToIssue(w http.ResponseWriter, r *http.Request) {
	issueID := chi.URLParam(r, "id")
	issue, ok := h.loadIssueForUser(w, r, issueID)
	if !ok {
		return
	}

	workspaceID := uuidToString(issue.WorkspaceID)
	// Default target: the caller, derived via resolveActor so an agent caller
	// (X-Agent-ID set) subscribes itself rather than the underlying member.
	callerActorType, callerActorID := h.resolveActor(r, requestUserID(r), workspaceID)
	targetUserType := callerActorType
	targetUserID := callerActorID
	var req struct {
		UserID   *string `json:"user_id"`
		UserType *string `json:"user_type"`
	}
	if r.Body != nil {
		json.NewDecoder(r.Body).Decode(&req)
	}
	if req.UserID != nil && *req.UserID != "" {
		targetUserID = *req.UserID
	}
	if req.UserType != nil && *req.UserType != "" {
		targetUserType = *req.UserType
	}

	if !h.isWorkspaceEntity(r.Context(), targetUserType, targetUserID, workspaceID) {
		writeError(w, http.StatusForbidden, "target user is not a member of this workspace")
		return
	}
	if h.refuseGuestForOthers(w, r, workspaceID, callerActorType, callerActorID, targetUserType, targetUserID) {
		return
	}

	// Explicit action, so this CLEARS any earlier opt-out tombstone — the user
	// is overriding their own unsubscribe. Rule-driven subscribes deliberately
	// cannot do that (see AddIssueSubscriber).
	err := h.Queries.SubscribeToIssueExplicitly(r.Context(), db.SubscribeToIssueExplicitlyParams{
		IssueID:  issue.ID,
		UserType: targetUserType,
		UserID:   parseUUID(targetUserID),
		Reason:   "manual",
	})
	if err != nil {
		writeError(w, http.StatusInternalServerError, "failed to subscribe")
		return
	}

	h.publish(protocol.EventSubscriberAdded, workspaceID, callerActorType, callerActorID, map[string]any{
		"issue_id":  issueID,
		"user_type": targetUserType,
		"user_id":   targetUserID,
		"reason":    "manual",
	})

	writeJSON(w, http.StatusOK, map[string]bool{"subscribed": true})
}

// refuseGuestForOthers writes a 403 when a guest targets a subscription other
// than its own. Subscribing a member notifies them and unsubscribing one hides
// replies and mentions from them, and a subtree may reach past the guest's
// projects: none of that is a guest's to decide for someone else. Both ids
// must already have passed isWorkspaceEntity, as parseUUID panics otherwise.
func (h *Handler) refuseGuestForOthers(w http.ResponseWriter, r *http.Request, workspaceID, callerType, callerID, targetType, targetID string) bool {
	if targetType == callerType && uuidToString(parseUUID(targetID)) == uuidToString(parseUUID(callerID)) {
		return false
	}
	if !h.isGuest(r, workspaceID, requestUserID(r)) {
		return false
	}
	writeError(w, http.StatusForbidden, "guests can only change their own subscription")
	return true
}

// UnsubscribeFromIssue removes a user's subscription from an issue.
// If request body contains user_id, unsubscribes that user; otherwise unsubscribes the caller.
func (h *Handler) UnsubscribeFromIssue(w http.ResponseWriter, r *http.Request) {
	h.unsubscribeFromIssue(w, r, false)
}

// UnsubscribeFromIssueSubtree leaves this issue AND every descendant, and —
// via the ancestor opt-out check the delegated rule runs — keeps future
// children of this tree from re-subscribing the user (MUL-5483).
//
// This is a SEPARATE ROUTE rather than a flag on /unsubscribe on purpose.
// Frontend staging deploys automatically on merge while backend staging is
// deployed by hand, so a new client routinely talks to an older server. A
// server that predates this feature decodes an unknown "subtree": true into
// nothing, unsubscribes the root only, and answers 200 — the user is told the
// whole tree is muted while every existing and future child keeps notifying.
// An unknown ROUTE 404s instead, so the client fails loudly and the user can
// retry rather than trusting a silent no-op.
func (h *Handler) UnsubscribeFromIssueSubtree(w http.ResponseWriter, r *http.Request) {
	h.unsubscribeFromIssue(w, r, true)
}

func (h *Handler) unsubscribeFromIssue(w http.ResponseWriter, r *http.Request, subtree bool) {
	issueID := chi.URLParam(r, "id")
	issue, ok := h.loadIssueForUser(w, r, issueID)
	if !ok {
		return
	}

	workspaceID := uuidToString(issue.WorkspaceID)
	// Default target: the caller, derived via resolveActor so an agent caller
	// (X-Agent-ID set) unsubscribes itself rather than the underlying member.
	callerActorType, callerActorID := h.resolveActor(r, requestUserID(r), workspaceID)
	targetUserType := callerActorType
	targetUserID := callerActorID
	var req struct {
		UserID   *string `json:"user_id"`
		UserType *string `json:"user_type"`
	}
	if r.Body != nil {
		json.NewDecoder(r.Body).Decode(&req)
	}
	if req.UserID != nil && *req.UserID != "" {
		targetUserID = *req.UserID
	}
	if req.UserType != nil && *req.UserType != "" {
		targetUserType = *req.UserType
	}

	if !h.isWorkspaceEntity(r.Context(), targetUserType, targetUserID, workspaceID) {
		writeError(w, http.StatusForbidden, "target user is not a member of this workspace")
		return
	}

	// Canonicalize before the target reaches either the advisory lock or a
	// broadcast. The lock keys on the UUID value, and clients dedupe on the
	// user_id string, so an uppercase request must not spell either one
	// differently from the delegated rule's canonical form
	// (MUL-5483 review round 8).
	targetUserID = uuidToString(parseUUID(targetUserID))

	if h.refuseGuestForOthers(w, r, workspaceID, callerActorType, callerActorID, targetUserType, targetUserID) {
		return
	}

	// Every issue this call actually left. The subtree variant reports the whole
	// set so each one gets its own broadcast: a client with a CHILD issue open
	// never sees the root's event, and would otherwise keep showing a
	// subscription the server has already retired.
	removed := []string{issueID}
	if subtree {
		// A subtree opt-out is only meaningful if it also covers children the
		// agent files a moment later, so it must not interleave with the
		// delegated rule's eligibility check. Both take the same
		// (workspace, user) lock for the length of their transaction; without
		// it a child created between the tombstone write and the rule's read
		// comes back as an active watcher (MUL-5483 review round 7).
		ids, err := h.unsubscribeSubtreeSerialized(r.Context(), workspaceID, issue.ID, targetUserType, targetUserID)
		if errors.Is(err, errTargetNoLongerMember) {
			writeError(w, http.StatusForbidden, "target user is not a member of this workspace")
			return
		}
		if err != nil {
			writeError(w, http.StatusInternalServerError, "failed to unsubscribe")
			return
		}
		removed = removed[:0]
		for _, id := range ids {
			removed = append(removed, uuidToString(id))
		}
	} else if err := h.Queries.RemoveIssueSubscriber(r.Context(), db.RemoveIssueSubscriberParams{
		IssueID:  issue.ID,
		UserType: targetUserType,
		UserID:   parseUUID(targetUserID),
	}); err != nil {
		writeError(w, http.StatusInternalServerError, "failed to unsubscribe")
		return
	}

	for _, id := range removed {
		h.publish(protocol.EventSubscriberRemoved, workspaceID, callerActorType, callerActorID, map[string]any{
			"issue_id":  id,
			"user_type": targetUserType,
			"user_id":   targetUserID,
		})
	}

	writeJSON(w, http.StatusOK, map[string]bool{"subscribed": false})
}

// UndoUnsubscribeFromIssue reverses the caller's own issue-scope unsubscribe,
// restoring the subscription as it was (see UndoIssueUnsubscribe) rather than
// subscribing again: a member who left a commenter or delegated subscription
// gets that back, not a manual one that delivers every event. It acts on the
// caller only. A separate route, so an older server answers 404 instead of
// quietly doing something else (as UnsubscribeFromIssueSubtree explains).
// 409 when there is no opt-out to undo, e.g. it was already reversed.
func (h *Handler) UndoUnsubscribeFromIssue(w http.ResponseWriter, r *http.Request) {
	issueID := chi.URLParam(r, "id")
	issue, ok := h.loadIssueForUser(w, r, issueID)
	if !ok {
		return
	}
	workspaceID := uuidToString(issue.WorkspaceID)
	actorType, actorID := h.resolveActor(r, requestUserID(r), workspaceID)
	actorID = uuidToString(parseUUID(actorID))

	row, err := h.Queries.UndoIssueUnsubscribe(r.Context(), db.UndoIssueUnsubscribeParams{
		IssueID:  issue.ID,
		UserType: actorType,
		UserID:   parseUUID(actorID),
	})
	if err != nil {
		writeError(w, http.StatusInternalServerError, "failed to undo unsubscribe")
		return
	}

	reason := row.RevivedReason
	if row.DroppedOptOut && actorType == "member" {
		projectSubscribers, err := h.Queries.ListProjectSubscribersForIssue(r.Context(), issue.ID)
		if err != nil {
			writeError(w, http.StatusInternalServerError, "failed to undo unsubscribe")
			return
		}
		for _, ps := range projectSubscribers {
			if uuidToString(ps.UserID) == actorID {
				reason = subscriberReasonProject
				break
			}
		}
	}
	if reason == "" && !row.DroppedOptOut {
		writeError(w, http.StatusConflict, "no unsubscribe to undo")
		return
	}

	if reason != "" {
		h.publish(protocol.EventSubscriberAdded, workspaceID, actorType, actorID, map[string]any{
			"issue_id":  issueID,
			"user_type": actorType,
			"user_id":   actorID,
			"reason":    reason,
		})
	}
	writeJSON(w, http.StatusOK, map[string]any{"subscribed": reason != "", "reason": reason})
}

// errTargetNoLongerMember reports that the target left the workspace between
// the handler's pre-check and the serialized write, so the caller can answer
// 403 exactly as the pre-check would have.
var errTargetNoLongerMember = errors.New("target user is no longer a workspace member")

// unsubscribeSubtreeSerialized tombstones the tree inside the same
// (workspace, user) serialization boundary the delegated auto-subscribe rule
// uses, and returns every issue it actually retired.
func (h *Handler) unsubscribeSubtreeSerialized(
	ctx context.Context, workspaceID string, rootID pgtype.UUID, userType, userID string,
) ([]pgtype.UUID, error) {
	tx, err := h.TxStarter.Begin(ctx)
	if err != nil {
		return nil, err
	}
	defer tx.Rollback(ctx)
	qtx := h.Queries.WithTx(tx)

	if err := qtx.LockSubscriberWrites(ctx, db.LockSubscriberWritesParams{
		WorkspaceID: parseUUID(workspaceID),
		UserID:      parseUUID(userID),
	}); err != nil {
		return nil, err
	}

	// The membership pre-check in the caller ran against its own snapshot,
	// before this transaction existed — it describes the past. A revoke that
	// commits in between clears this user's subscriptions and deletes their
	// member row, and writing a tombstone behind it would leave an opt-out that
	// outlives the membership and is inherited on re-invite. Re-assert it here,
	// holding the row, now that the lock guarantees no revoke can interleave
	// (MUL-5483 review round 8).
	//
	// Members only: an agent target has no member row, and revoke's subscription
	// cleanup is member-scoped, so the outlives-membership problem does not
	// arise for agents.
	if userType == "member" {
		if _, err := qtx.LockActiveMember(ctx, db.LockActiveMemberParams{
			UserID:      parseUUID(userID),
			WorkspaceID: parseUUID(workspaceID),
		}); err != nil {
			if errors.Is(err, pgx.ErrNoRows) {
				return nil, errTargetNoLongerMember
			}
			return nil, err
		}
	}

	ids, err := qtx.UnsubscribeFromIssueSubtree(ctx, db.UnsubscribeFromIssueSubtreeParams{
		ID:       rootID,
		UserType: userType,
		UserID:   parseUUID(userID),
	})
	if err != nil {
		return nil, err
	}
	if err := tx.Commit(ctx); err != nil {
		return nil, err
	}
	return ids, nil
}