|
| 1 | +// Copyright 2024 EMQ Technologies Co., Ltd. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package httpserver |
| 16 | + |
| 17 | +import ( |
| 18 | + "context" |
| 19 | + "fmt" |
| 20 | + "net/http" |
| 21 | + "sync" |
| 22 | + |
| 23 | + "github.com/lf-edge/ekuiper/contract/v2/api" |
| 24 | + |
| 25 | + "github.com/lf-edge/ekuiper/v2/internal/conf" |
| 26 | + "github.com/lf-edge/ekuiper/v2/internal/io/memory/pubsub" |
| 27 | +) |
| 28 | + |
| 29 | +const ( |
| 30 | + SseTopicPrefix = "$$sse/" |
| 31 | +) |
| 32 | + |
| 33 | +type sseEndpointContext struct { |
| 34 | + wg *sync.WaitGroup |
| 35 | + conns map[int64]context.CancelFunc |
| 36 | +} |
| 37 | + |
| 38 | +func recvSseTopic(endpoint string) string { |
| 39 | + return fmt.Sprintf("%s/server/recv/%s", SseTopicPrefix, endpoint) |
| 40 | +} |
| 41 | + |
| 42 | +func sendSseTopic(endpoint string) string { |
| 43 | + return fmt.Sprintf("%s/server/send/%s", SseTopicPrefix, endpoint) |
| 44 | +} |
| 45 | + |
| 46 | +func RegisterSSEEndpoint(ctx api.StreamContext, endpoint string) (string, string, error) { |
| 47 | + managerLock.RLock() |
| 48 | + m := manager |
| 49 | + managerLock.RUnlock() |
| 50 | + if m == nil { |
| 51 | + return "", "", fmt.Errorf("http server is not running") |
| 52 | + } |
| 53 | + return m.RegisterSSEEndpoint(ctx, endpoint) |
| 54 | +} |
| 55 | + |
| 56 | +func UnRegisterSSEEndpoint(endpoint string) { |
| 57 | + managerLock.RLock() |
| 58 | + m := manager |
| 59 | + managerLock.RUnlock() |
| 60 | + if m == nil { |
| 61 | + return |
| 62 | + } |
| 63 | + sctx := m.UnRegisterSSEEndpoint(endpoint) |
| 64 | + if sctx != nil { |
| 65 | + // wait all connections to close |
| 66 | + sctx.wg.Wait() |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +func (m *GlobalServerManager) RegisterSSEEndpoint(ctx api.StreamContext, endpoint string) (string, string, error) { |
| 71 | + conf.Log.Infof("sse endpoint %v register", endpoint) |
| 72 | + m.Lock() |
| 73 | + defer m.Unlock() |
| 74 | + rTopic := recvSseTopic(endpoint) |
| 75 | + sTopic := sendSseTopic(endpoint) |
| 76 | + pubsub.CreatePub(rTopic) |
| 77 | + |
| 78 | + m.routes[endpoint] = func(w http.ResponseWriter, r *http.Request) { |
| 79 | + flusher, ok := w.(http.Flusher) |
| 80 | + if !ok { |
| 81 | + http.Error(w, "Streaming unsupported!", http.StatusInternalServerError) |
| 82 | + return |
| 83 | + } |
| 84 | + |
| 85 | + w.Header().Set("Content-Type", "text/event-stream") |
| 86 | + w.Header().Set("Cache-Control", "no-cache") |
| 87 | + w.Header().Set("Connection", "keep-alive") |
| 88 | + w.Header().Set("Access-Control-Allow-Origin", "*") |
| 89 | + flusher.Flush() |
| 90 | + |
| 91 | + // Create a cancel context for this specific connection |
| 92 | + connCtx, cancel := context.WithCancel(r.Context()) |
| 93 | + connID := int64(m.FetchInstanceID()) |
| 94 | + wg, ok := m.AddSSEConnection(endpoint, connID, cancel) |
| 95 | + if !ok { |
| 96 | + return |
| 97 | + } |
| 98 | + defer func() { |
| 99 | + m.CloseSSEConnection(endpoint, connID) |
| 100 | + wg.Done() |
| 101 | + }() |
| 102 | + |
| 103 | + // Create a subscription to the send topic |
| 104 | + // The sourceID must be unique for each connection to ensure all clients receive the message |
| 105 | + sourceID := fmt.Sprintf("sse/send/%v", connID) |
| 106 | + ch := pubsub.CreateSub(sTopic, nil, sourceID, 1024) |
| 107 | + defer pubsub.CloseSourceConsumerChannel(sTopic, sourceID) |
| 108 | + |
| 109 | + conf.Log.Infof("sse client connected to %s", endpoint) |
| 110 | + |
| 111 | + for { |
| 112 | + select { |
| 113 | + case <-connCtx.Done(): |
| 114 | + conf.Log.Infof("sse client disconnected from %s", endpoint) |
| 115 | + return |
| 116 | + case d, ok := <-ch: |
| 117 | + if !ok { |
| 118 | + conf.Log.Infof("sse channel closed for %s", endpoint) |
| 119 | + return |
| 120 | + } |
| 121 | + data, ok := d.([]byte) |
| 122 | + if !ok || data == nil { |
| 123 | + continue |
| 124 | + } |
| 125 | + fmt.Fprintf(w, "data: %s\n\n", string(data)) |
| 126 | + flusher.Flush() |
| 127 | + } |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + m.sseEndpoint[endpoint] = &sseEndpointContext{ |
| 132 | + wg: &sync.WaitGroup{}, |
| 133 | + conns: make(map[int64]context.CancelFunc), |
| 134 | + } |
| 135 | + m.router.HandleFunc(endpoint, func(w http.ResponseWriter, r *http.Request) { |
| 136 | + m.RLock() |
| 137 | + h, ok := m.routes[endpoint] |
| 138 | + m.RUnlock() |
| 139 | + if ok { |
| 140 | + h(w, r) |
| 141 | + } else { |
| 142 | + w.WriteHeader(http.StatusNotFound) |
| 143 | + } |
| 144 | + }) |
| 145 | + |
| 146 | + conf.Log.Infof("sse endpoint %v registered success", endpoint) |
| 147 | + return rTopic, sTopic, nil |
| 148 | +} |
| 149 | + |
| 150 | +func (m *GlobalServerManager) AddSSEConnection(endpoint string, connID int64, cancel context.CancelFunc) (*sync.WaitGroup, bool) { |
| 151 | + m.Lock() |
| 152 | + defer m.Unlock() |
| 153 | + sctx, ok := m.sseEndpoint[endpoint] |
| 154 | + if !ok { |
| 155 | + return nil, false |
| 156 | + } |
| 157 | + sctx.conns[connID] = cancel |
| 158 | + sctx.wg.Add(1) |
| 159 | + return sctx.wg, true |
| 160 | +} |
| 161 | + |
| 162 | +func (m *GlobalServerManager) CloseSSEConnection(endpoint string, connID int64) { |
| 163 | + m.Lock() |
| 164 | + defer m.Unlock() |
| 165 | + sctx, ok := m.sseEndpoint[endpoint] |
| 166 | + if !ok { |
| 167 | + return |
| 168 | + } |
| 169 | + delete(sctx.conns, connID) |
| 170 | +} |
| 171 | + |
| 172 | +func (m *GlobalServerManager) UnRegisterSSEEndpoint(endpoint string) *sseEndpointContext { |
| 173 | + conf.Log.Infof("sse endpoint %v unregister", endpoint) |
| 174 | + pubsub.RemovePub(recvSseTopic(endpoint)) |
| 175 | + m.Lock() |
| 176 | + defer m.Unlock() |
| 177 | + |
| 178 | + sctx, ok := m.sseEndpoint[endpoint] |
| 179 | + if !ok { |
| 180 | + delete(m.routes, endpoint) |
| 181 | + return nil |
| 182 | + } |
| 183 | + // Cancel all active connections |
| 184 | + for _, cancel := range sctx.conns { |
| 185 | + cancel() |
| 186 | + } |
| 187 | + delete(m.sseEndpoint, endpoint) |
| 188 | + delete(m.routes, endpoint) |
| 189 | + return sctx |
| 190 | +} |
0 commit comments