code: func (s *StanServer) endSubSentAndAckReplication(sub *subState, unsub bool) {
  	var ch chan struct{}
  	var data []byte
  
  	sub.Lock()
  	r := sub.replicate
  	if r == nil {
  		sub.Unlock()
  		return
  	}
  	if !unsub && (sub.IsDurable || sub.qstate != nil) && len(r.sent)+len(r.ack) > 0 {
  		data = createSubSentAndAckProto(sub, r)
  	}
  	// If the replicator is about to apply, or in middle of it, we
  	// want to wait for it to finish regardless if we have to replicate
  	// something or not. We are not expecting this situation to occur often.
  	if r.applying {
  		ch = make(chan struct{}, 1)
  		s.ssarepl.gates.Store(sub, ch)
  	}
  	s.clearSentAndAck(sub)
  	sub.Unlock()
  
  	if ch != nil {
  		<-ch
  	}
  	if data != nil {
  		s.raft.Apply(data, 0)
  	}
  }
docs: // This is called when a subscription is closed or unsubscribed, or
  // a connection is closed, but prior to the RAFT replication of such
  // event.
  // Depending on the type of event, we want to make sure that we flush
  // the possibly remaning sent/ack events.