Просмотр исходного кода

Use visitor instead of UserID in topicSubscription

Karmanyaah Malhotra 3 лет назад
Родитель
Сommit
d686e1ee77
2 измененных файлов с 9 добавлено и 8 удалено
  1. 2 2
      server/server.go
  2. 7 6
      server/topic.go

+ 2 - 2
server/server.go

@@ -1023,7 +1023,7 @@ func (s *Server) handleSubscribeHTTP(w http.ResponseWriter, r *http.Request, v *
 	defer cancel()
 	subscriberIDs := make([]int, 0)
 	for _, t := range topics {
-		subscriberIDs = append(subscriberIDs, t.Subscribe(sub, v.MaybeUserID(), cancel))
+		subscriberIDs = append(subscriberIDs, t.Subscribe(sub, v, cancel))
 	}
 	defer func() {
 		for i, subscriberID := range subscriberIDs {
@@ -1155,7 +1155,7 @@ func (s *Server) handleSubscribeWS(w http.ResponseWriter, r *http.Request, v *vi
 	}
 	subscriberIDs := make([]int, 0)
 	for _, t := range topics {
-		subscriberIDs = append(subscriberIDs, t.Subscribe(sub, v.MaybeUserID(), cancel))
+		subscriberIDs = append(subscriberIDs, t.Subscribe(sub, v, cancel))
 	}
 	defer func() {
 		for i, subscriberID := range subscriberIDs {

+ 7 - 6
server/topic.go

@@ -15,8 +15,8 @@ type topic struct {
 }
 
 type topicSubscriber struct {
-	userID     string // User ID associated with this subscription, may be empty
 	subscriber subscriber
+	visitor    *visitor // User ID associated with this subscription, may be empty
 	cancel     func()
 }
 
@@ -32,12 +32,12 @@ func newTopic(id string) *topic {
 }
 
 // Subscribe subscribes to this topic
-func (t *topic) Subscribe(s subscriber, userID string, cancel func()) int {
+func (t *topic) Subscribe(s subscriber, visitor *visitor, cancel func()) int {
 	t.mu.Lock()
 	defer t.mu.Unlock()
 	subscriberID := rand.Int()
 	t.subscribers[subscriberID] = &topicSubscriber{
-		userID:     userID, // May be empty
+		visitor:    visitor, // May be empty
 		subscriber: s,
 		cancel:     cancel,
 	}
@@ -87,8 +87,9 @@ func (t *topic) CancelSubscribers(exceptUserID string) {
 	t.mu.Lock()
 	defer t.mu.Unlock()
 	for _, s := range t.subscribers {
-		if s.userID != exceptUserID {
-			log.Tag(tagSubscribe).Field("topic", t.ID).Debug("Canceling subscriber %s", s.userID)
+		if s.visitor.MaybeUserID() != exceptUserID {
+			// TODO: Shouldn't this log the IP for anonymous visitors? It was s.userID before my change.
+			log.Tag(tagSubscribe).Field("topic", t.ID).Debug("Canceling subscriber %s", s.visitor.MaybeUserID())
 			s.cancel()
 		}
 	}
@@ -101,7 +102,7 @@ func (t *topic) subscribersCopy() map[int]*topicSubscriber {
 	subscribers := make(map[int]*topicSubscriber)
 	for k, sub := range t.subscribers {
 		subscribers[k] = &topicSubscriber{
-			userID:     sub.userID,
+			visitor:    sub.visitor,
 			subscriber: sub.subscriber,
 			cancel:     sub.cancel,
 		}