feat(collab): redesign note collaboration with REST auto-save, opt-in live session, and block locking
MindSift CI & Docker Release / Build, Test in Container & Push (push) Successful in 59s

This commit is contained in:
sandrodach committed 2026-10-27 14:02:38 +01:00
1 parent 50b017f387
commit 0e06cc5577
11 files changed
+1373 -239

No files matched your search

+196
View File
@@ -145,6 +145,13 @@ func (s *Server) Router() http.Handler {
r.Post("/api/v1/documents/{id}/shares", s.handleCreateDocShare)
r.Delete("/api/v1/documents/{id}/shares/{userId}", s.handleDeleteDocShare)
// Document Locks & Live-Collaboration Sessions
r.Get("/api/v1/documents/{id}/locks", s.handleGetDocLocks)
r.Post("/api/v1/documents/{id}/blocks/{blockId}/lock", s.handleLockBlock)
r.Post("/api/v1/documents/{id}/blocks/{blockId}/unlock", s.handleUnlockBlock)
r.Post("/api/v1/documents/{id}/live/start", s.handleStartLiveSession)
r.Post("/api/v1/documents/{id}/live/end", s.handleEndLiveSession)
// Shared Lists & Realtime Collaboration
r.Get("/api/v1/lists", s.handleGetAllLists)
r.Post("/api/v1/lists", s.handleCreateList)
@@ -923,6 +930,19 @@ func (s *Server) handleUpdateDocument(w http.ResponseWriter, r *http.Request) {
userID := auth.GetUserID(r.Context())
docID := chi.URLParam(r, "id")
if s.wsHub != nil {
if ls := s.wsHub.GetLiveSession(docID); ls != nil && ls.InitiatorID != userID {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusLocked)
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"error": "Dokument wird aktuell in einer Live-Sitzung bearbeitet",
"lockedBy": ls.InitiatorName,
"isLocked": true,
})
return
}
}
var req struct {
Title *string `json:"title"`
Icon *string `json:"icon"`
@@ -954,6 +974,19 @@ func (s *Server) handlePatchDocumentBlocks(w http.ResponseWriter, r *http.Reques
userID := auth.GetUserID(r.Context())
docID := chi.URLParam(r, "id")
if s.wsHub != nil {
if ls := s.wsHub.GetLiveSession(docID); ls != nil && ls.InitiatorID != userID {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusLocked)
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"error": "Dokument wird aktuell in einer Live-Sitzung bearbeitet",
"lockedBy": ls.InitiatorName,
"isLocked": true,
})
return
}
}
var req domain.DocBlocksPatchRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "Ungültiges JSON")
@@ -1381,6 +1414,169 @@ func (s *Server) handleGetCollaborators(w http.ResponseWriter, r *http.Request)
writeJSON(w, http.StatusOK, users)
}
// --- DOCUMENT LOCKS & LIVE COLLABORATION SESSIONS ---
func (s *Server) handleGetDocLocks(w http.ResponseWriter, r *http.Request) {
docID := chi.URLParam(r, "id")
var blockLocks []domain.BlockLockInfo
var liveSession *domain.LiveSessionInfo
if s.wsHub != nil {
blockLocks = s.wsHub.GetDocBlockLocks(docID)
liveSession = s.wsHub.GetLiveSession(docID)
}
if blockLocks == nil {
blockLocks = []domain.BlockLockInfo{}
}
writeJSON(w, http.StatusOK, domain.DocLocksResponse{
DocID: docID,
BlockLocks: blockLocks,
LiveSession: liveSession,
})
}
func (s *Server) handleLockBlock(w http.ResponseWriter, r *http.Request) {
userID := auth.GetUserID(r.Context())
docID := chi.URLParam(r, "id")
blockID := chi.URLParam(r, "blockId")
// If live session is active by someone else, reject
if s.wsHub != nil {
if ls := s.wsHub.GetLiveSession(docID); ls != nil && ls.InitiatorID != userID {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusLocked)
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"error": "Dokument wird aktuell in einer Live-Sitzung bearbeitet",
"lockedBy": ls.InitiatorName,
"isLocked": true,
})
return
}
}
user, _ := s.store.GetUserByID(userID)
userName := "Anonym"
userColor := "#3b82f6"
if user != nil {
if user.DisplayName != "" {
userName = user.DisplayName
} else {
userName = user.Username
}
}
var req struct {
UserColor string `json:"userColor"`
TTLSeconds int `json:"ttlSeconds"`
}
_ = json.NewDecoder(r.Body).Decode(&req)
if req.UserColor != "" {
userColor = req.UserColor
}
ttl := 30 * time.Second
if req.TTLSeconds > 5 && req.TTLSeconds <= 120 {
ttl = time.Duration(req.TTLSeconds) * time.Second
}
if s.wsHub != nil {
lockInfo, ok, existing := s.wsHub.AcquireBlockLock(docID, blockID, userID, userName, userColor, ttl)
if !ok && existing != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusConflict)
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"error": "Block ist von anderem Benutzer gesperrt",
"lockedBy": existing.UserName,
"lock": existing,
})
return
}
s.wsHub.BroadcastRoom("doc:"+docID, "DOC_BLOCK_LOCKED", lockInfo, nil)
writeJSON(w, http.StatusOK, map[string]interface{}{
"success": true,
"lock": lockInfo,
})
return
}
writeJSON(w, http.StatusOK, map[string]bool{"success": true})
}
func (s *Server) handleUnlockBlock(w http.ResponseWriter, r *http.Request) {
userID := auth.GetUserID(r.Context())
docID := chi.URLParam(r, "id")
blockID := chi.URLParam(r, "blockId")
if s.wsHub != nil {
s.wsHub.ReleaseBlockLock(docID, blockID, userID)
s.wsHub.BroadcastRoom("doc:"+docID, "DOC_BLOCK_UNLOCKED", map[string]string{
"docId": docID,
"blockId": blockID,
"userId": userID,
}, nil)
}
writeJSON(w, http.StatusOK, map[string]bool{"success": true})
}
func (s *Server) handleStartLiveSession(w http.ResponseWriter, r *http.Request) {
userID := auth.GetUserID(r.Context())
docID := chi.URLParam(r, "id")
user, _ := s.store.GetUserByID(userID)
userName := "Anonym"
if user != nil {
if user.DisplayName != "" {
userName = user.DisplayName
} else {
userName = user.Username
}
}
ttl := 120 * time.Second // 2 min lease with heartbeat while active
if s.wsHub != nil {
info, ok, existing := s.wsHub.StartLiveSession(docID, userID, userName, ttl)
if !ok && existing != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusConflict)
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"error": "Live-Sitzung bereits von anderem Benutzer aktiv",
"session": existing,
"initiator": existing.InitiatorName,
})
return
}
s.wsHub.BroadcastRoom("doc:"+docID, "DOC_LIVE_STARTED", info, nil)
if users, err := s.store.GetAuthorizedDocUsers(docID); err == nil {
for _, uid := range users {
s.wsHub.BroadcastToUser(uid, "DOC_LIVE_STARTED", info)
}
}
writeJSON(w, http.StatusOK, map[string]interface{}{
"success": true,
"session": info,
})
return
}
writeJSON(w, http.StatusOK, map[string]bool{"success": true})
}
func (s *Server) handleEndLiveSession(w http.ResponseWriter, r *http.Request) {
userID := auth.GetUserID(r.Context())
docID := chi.URLParam(r, "id")
if s.wsHub != nil {
s.wsHub.EndLiveSession(docID, userID)
evt := map[string]string{
"docId": docID,
"userId": userID,
}
s.wsHub.BroadcastRoom("doc:"+docID, "DOC_LIVE_ENDED", evt, nil)
if users, err := s.store.GetAuthorizedDocUsers(docID); err == nil {
for _, uid := range users {
s.wsHub.BroadcastToUser(uid, "DOC_LIVE_ENDED", evt)
}
}
}
writeJSON(w, http.StatusOK, map[string]bool{"success": true})
}
// --- DOCUMENT REALTIME WEBSOCKET ROOM ---
func (s *Server) authenticateUserFromReq(r *http.Request) string {
+121
View File
@@ -1295,6 +1295,127 @@ func TestTokenBlacklistingAndTokenVersionRevocation(t *testing.T) {
}
}
func TestBlockLockingAndLiveSessionGuards(t *testing.T) {
srv, store, _ := setupTestServer(t)
router := srv.Router()
userA, _ := store.CreateUser("user_a_lock@example.com", "hash", "User A", "member")
tokenA, _ := auth.GenerateToken(srv.cfg.JWTSecret, userA.ID, userA.Email, userA.DisplayName, userA.TokenVersion)
userB, _ := store.CreateUser("user_b_lock@example.com", "hash", "User B", "member")
tokenB, _ := auth.GenerateToken(srv.cfg.JWTSecret, userB.ID, userB.Email, userB.DisplayName, userB.TokenVersion)
// Create document owned by User A, shared with User B
blocks := []domain.DocumentBlock{
{ID: "b1", Type: "bullet", Content: "Row 1", Level: 0},
{ID: "b2", Type: "bullet", Content: "Row 2", Level: 0},
}
doc, err := store.CreateDocument(userA.ID, "", "Lock Test Doc", "📝", "", blocks, nil, false)
if err != nil {
t.Fatalf("CreateDocument failed: %v", err)
}
_, _ = store.CreateDocShare(userA.ID, doc.ID, userB.ID, "write")
// 1. Initial locks should be empty
req := httptest.NewRequest(http.MethodGet, "/api/v1/documents/"+doc.ID+"/locks", nil)
req.Header.Set("Authorization", "Bearer "+tokenA)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("get locks failed: %d", rec.Code)
}
var locksResp domain.DocLocksResponse
_ = json.Unmarshal(rec.Body.Bytes(), &locksResp)
if len(locksResp.BlockLocks) != 0 || locksResp.LiveSession != nil {
t.Fatalf("expected 0 locks initially, got %v", locksResp)
}
// 2. User A locks block b1
req = httptest.NewRequest(http.MethodPost, "/api/v1/documents/"+doc.ID+"/blocks/b1/lock", bytes.NewReader([]byte(`{"ttlSeconds": 30}`)))
req.Header.Set("Authorization", "Bearer "+tokenA)
req.Header.Set("Content-Type", "application/json")
rec = httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("user A lock b1 failed: %d, body: %s", rec.Code, rec.Body.String())
}
// 3. User B tries to lock b1 -> must receive 409 Conflict
req = httptest.NewRequest(http.MethodPost, "/api/v1/documents/"+doc.ID+"/blocks/b1/lock", bytes.NewReader([]byte(`{"ttlSeconds": 30}`)))
req.Header.Set("Authorization", "Bearer "+tokenB)
req.Header.Set("Content-Type", "application/json")
rec = httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusConflict {
t.Fatalf("expected 409 Conflict for user B on b1, got %d", rec.Code)
}
// 4. User A unlocks b1
req = httptest.NewRequest(http.MethodPost, "/api/v1/documents/"+doc.ID+"/blocks/b1/unlock", nil)
req.Header.Set("Authorization", "Bearer "+tokenA)
rec = httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("user A unlock b1 failed: %d", rec.Code)
}
// 5. User B can now lock b1
req = httptest.NewRequest(http.MethodPost, "/api/v1/documents/"+doc.ID+"/blocks/b1/lock", bytes.NewReader([]byte(`{"ttlSeconds": 30}`)))
req.Header.Set("Authorization", "Bearer "+tokenB)
rec = httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("user B lock b1 should succeed now, got %d", rec.Code)
}
// User B unlocks b1
req = httptest.NewRequest(http.MethodPost, "/api/v1/documents/"+doc.ID+"/blocks/b1/unlock", nil)
req.Header.Set("Authorization", "Bearer "+tokenB)
rec = httptest.NewRecorder()
router.ServeHTTP(rec, req)
// 6. User A starts a Live-Session on doc
req = httptest.NewRequest(http.MethodPost, "/api/v1/documents/"+doc.ID+"/live/start", nil)
req.Header.Set("Authorization", "Bearer "+tokenA)
rec = httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("user A start live session failed: %d, body: %s", rec.Code, rec.Body.String())
}
// 7. User B tries to patch document blocks while User A's live session is active -> must receive 423 Locked!
patchBody, _ := json.Marshal(domain.DocBlocksPatchRequest{
Upserted: []domain.DocumentBlock{{ID: "b2", Content: "Hacked by User B"}},
})
req = httptest.NewRequest(http.MethodPatch, "/api/v1/documents/"+doc.ID+"/blocks", bytes.NewReader(patchBody))
req.Header.Set("Authorization", "Bearer "+tokenB)
req.Header.Set("Content-Type", "application/json")
rec = httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusLocked {
t.Fatalf("expected 423 Locked for User B while live session is active, got %d, body: %s", rec.Code, rec.Body.String())
}
// 8. User A ends the Live-Session
req = httptest.NewRequest(http.MethodPost, "/api/v1/documents/"+doc.ID+"/live/end", nil)
req.Header.Set("Authorization", "Bearer "+tokenA)
rec = httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("user A end live session failed: %d", rec.Code)
}
// 9. User B can now edit again
req = httptest.NewRequest(http.MethodPatch, "/api/v1/documents/"+doc.ID+"/blocks", bytes.NewReader(patchBody))
req.Header.Set("Authorization", "Bearer "+tokenB)
req.Header.Set("Content-Type", "application/json")
rec = httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("User B edit should succeed after live session ended, got %d, body: %s", rec.Code, rec.Body.String())
}
}
+23
View File
@@ -344,6 +344,29 @@ type DocLockInfo struct {
ExpiresAt string `json:"expiresAt"`
}
type BlockLockInfo struct {
DocID string `json:"docId"`
BlockID string `json:"blockId"`
UserID string `json:"userId"`
UserName string `json:"userName"`
UserColor string `json:"userColor,omitempty"`
ExpiresAt string `json:"expiresAt"`
}
type LiveSessionInfo struct {
DocID string `json:"docId"`
InitiatorID string `json:"initiatorId"`
InitiatorName string `json:"initiatorName"`
StartedAt string `json:"startedAt"`
ExpiresAt string `json:"expiresAt"`
}
type DocLocksResponse struct {
DocID string `json:"docId"`
BlockLocks []BlockLockInfo `json:"blockLocks"`
LiveSession *LiveSessionInfo `json:"liveSession,omitempty"`
}
type Document struct {
ID string `json:"id"`
UserID string `json:"userId"`
+235
View File
@@ -92,6 +92,24 @@ type docLockItem struct {
expiresAt time.Time
}
type blockLockItem struct {
docID string
blockID string
userID string
userName string
userColor string
lockedAt time.Time
expiresAt time.Time
}
type liveSessionItem struct {
docID string
initiatorID string
initiatorName string
startedAt time.Time
expiresAt time.Time
}
type DocStore interface {
LoadDocumentState(docID string) (string, []domain.DocumentBlock, error)
FlushDocumentState(docID string, title string, blocks []domain.DocumentBlock) error
@@ -106,6 +124,8 @@ type Hub struct {
sseUserRooms map[string]map[*SSEClient]bool
sseRooms map[string]map[*SSEClient]bool
locks map[string]*docLockItem
blockLocks map[string]*blockLockItem // key: docID + ":" + blockID
liveSessions map[string]*liveSessionItem // key: docID
docRooms map[string]*DocRoom
docStore DocStore
stopCleanup chan struct{}
@@ -121,6 +141,8 @@ func NewHub() *Hub {
sseUserRooms: make(map[string]map[*SSEClient]bool),
sseRooms: make(map[string]map[*SSEClient]bool),
locks: make(map[string]*docLockItem),
blockLocks: make(map[string]*blockLockItem),
liveSessions: make(map[string]*liveSessionItem),
docRooms: make(map[string]*DocRoom),
stopCleanup: make(chan struct{}),
}
@@ -459,6 +481,187 @@ func (h *Hub) GetDocLock(docID string) *domain.DocLockInfo {
}
}
// Block Locking Methods (Option B)
func (h *Hub) AcquireBlockLock(docID, blockID, userID, userName, userColor string, ttl time.Duration) (*domain.BlockLockInfo, bool, *domain.BlockLockInfo) {
h.mu.Lock()
defer h.mu.Unlock()
now := time.Now()
key := docID + ":" + blockID
existing, exists := h.blockLocks[key]
if exists && existing.expiresAt.After(now) {
if existing.userID != userID {
info := &domain.BlockLockInfo{
DocID: existing.docID,
BlockID: existing.blockID,
UserID: existing.userID,
UserName: existing.userName,
UserColor: existing.userColor,
ExpiresAt: existing.expiresAt.Format(time.RFC3339),
}
return nil, false, info
}
// Refresh lease
existing.expiresAt = now.Add(ttl)
if userName != "" {
existing.userName = userName
}
if userColor != "" {
existing.userColor = userColor
}
info := &domain.BlockLockInfo{
DocID: existing.docID,
BlockID: existing.blockID,
UserID: existing.userID,
UserName: existing.userName,
UserColor: existing.userColor,
ExpiresAt: existing.expiresAt.Format(time.RFC3339),
}
return info, true, nil
}
item := &blockLockItem{
docID: docID,
blockID: blockID,
userID: userID,
userName: userName,
userColor: userColor,
lockedAt: now,
expiresAt: now.Add(ttl),
}
h.blockLocks[key] = item
info := &domain.BlockLockInfo{
DocID: item.docID,
BlockID: item.blockID,
UserID: item.userID,
UserName: item.userName,
UserColor: item.userColor,
ExpiresAt: item.expiresAt.Format(time.RFC3339),
}
return info, true, nil
}
func (h *Hub) ReleaseBlockLock(docID, blockID, userID string) bool {
h.mu.Lock()
defer h.mu.Unlock()
key := docID + ":" + blockID
existing, exists := h.blockLocks[key]
if !exists {
return false
}
if userID != "" && existing.userID != userID && userID != "admin" {
return false
}
delete(h.blockLocks, key)
return true
}
func (h *Hub) GetDocBlockLocks(docID string) []domain.BlockLockInfo {
h.mu.RLock()
defer h.mu.RUnlock()
now := time.Now()
var result []domain.BlockLockInfo
prefix := docID + ":"
for k, l := range h.blockLocks {
if strings.HasPrefix(k, prefix) && l.expiresAt.After(now) {
result = append(result, domain.BlockLockInfo{
DocID: l.docID,
BlockID: l.blockID,
UserID: l.userID,
UserName: l.userName,
UserColor: l.userColor,
ExpiresAt: l.expiresAt.Format(time.RFC3339),
})
}
}
return result
}
// Live Session Methods (Opt-In Live Collaboration)
func (h *Hub) StartLiveSession(docID, userID, userName string, ttl time.Duration) (*domain.LiveSessionInfo, bool, *domain.LiveSessionInfo) {
h.mu.Lock()
defer h.mu.Unlock()
now := time.Now()
existing, exists := h.liveSessions[docID]
if exists && existing.expiresAt.After(now) {
if existing.initiatorID != userID {
info := &domain.LiveSessionInfo{
DocID: existing.docID,
InitiatorID: existing.initiatorID,
InitiatorName: existing.initiatorName,
StartedAt: existing.startedAt.Format(time.RFC3339),
ExpiresAt: existing.expiresAt.Format(time.RFC3339),
}
return nil, false, info
}
// Refresh lease
existing.expiresAt = now.Add(ttl)
info := &domain.LiveSessionInfo{
DocID: existing.docID,
InitiatorID: existing.initiatorID,
InitiatorName: existing.initiatorName,
StartedAt: existing.startedAt.Format(time.RFC3339),
ExpiresAt: existing.expiresAt.Format(time.RFC3339),
}
return info, true, nil
}
item := &liveSessionItem{
docID: docID,
initiatorID: userID,
initiatorName: userName,
startedAt: now,
expiresAt: now.Add(ttl),
}
h.liveSessions[docID] = item
info := &domain.LiveSessionInfo{
DocID: item.docID,
InitiatorID: item.initiatorID,
InitiatorName: item.initiatorName,
StartedAt: item.startedAt.Format(time.RFC3339),
ExpiresAt: item.expiresAt.Format(time.RFC3339),
}
return info, true, nil
}
func (h *Hub) EndLiveSession(docID, userID string) bool {
h.mu.Lock()
defer h.mu.Unlock()
existing, exists := h.liveSessions[docID]
if !exists {
return false
}
if userID != "" && existing.initiatorID != userID && userID != "admin" {
return false
}
delete(h.liveSessions, docID)
return true
}
func (h *Hub) GetLiveSession(docID string) *domain.LiveSessionInfo {
h.mu.RLock()
defer h.mu.RUnlock()
now := time.Now()
existing, exists := h.liveSessions[docID]
if !exists || existing.expiresAt.Before(now) {
return nil
}
return &domain.LiveSessionInfo{
DocID: existing.docID,
InitiatorID: existing.initiatorID,
InitiatorName: existing.initiatorName,
StartedAt: existing.startedAt.Format(time.RFC3339),
ExpiresAt: existing.expiresAt.Format(time.RFC3339),
}
}
func (h *Hub) cleanupLocksLoop() {
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
@@ -470,6 +673,7 @@ func (h *Hub) cleanupLocksLoop() {
case <-ticker.C:
h.mu.Lock()
now := time.Now()
var expiredDocIDs []string
for docID, l := range h.locks {
if l.expiresAt.Before(now) {
@@ -477,11 +681,42 @@ func (h *Hub) cleanupLocksLoop() {
delete(h.locks, docID)
}
}
type expBlock struct {
docID string
blockID string
}
var expiredBlocks []expBlock
for k, bl := range h.blockLocks {
if bl.expiresAt.Before(now) {
expiredBlocks = append(expiredBlocks, expBlock{docID: bl.docID, blockID: bl.blockID})
delete(h.blockLocks, k)
}
}
var expiredLiveSessions []string
for docID, ls := range h.liveSessions {
if ls.expiresAt.Before(now) {
expiredLiveSessions = append(expiredLiveSessions, docID)
delete(h.liveSessions, docID)
}
}
h.mu.Unlock()
for _, docID := range expiredDocIDs {
h.BroadcastToAll("DOC_UNLOCKED", map[string]string{"docId": docID, "doc_id": docID})
}
for _, b := range expiredBlocks {
h.BroadcastRoom("doc:"+b.docID, "DOC_BLOCK_UNLOCKED", map[string]string{
"docId": b.docID,
"blockId": b.blockID,
}, nil)
}
for _, docID := range expiredLiveSessions {
h.BroadcastRoom("doc:"+docID, "DOC_LIVE_ENDED", map[string]string{
"docId": docID,
}, nil)
}
}
}
}