MCPcopy Index your code
hub / github.com/coder/coder / watchChats

Method watchChats

coderd/exp_chats.go:173–224  ·  view source on GitHub ↗

EXPERIMENTAL: this endpoint is experimental and is subject to change. @Summary Watch chat events for a user via WebSockets @ID watch-chat-events-for-a-user-via-websockets @Security CoderSessionToken @Tags Chats @Produce json @Success 200 {object} codersdk.ChatWatchEvent @Router /api/experimental/ch

(rw http.ResponseWriter, r *http.Request)

Source from the content-addressed store, hash-verified

171// @Router /api/experimental/chats/watch [get]
172// @Description Experimental: this endpoint is subject to change.
173func (api *API) watchChats(rw http.ResponseWriter, r *http.Request) {
174 ctx := r.Context()
175 apiKey := httpmw.APIKey(r)
176 logger := api.Logger.Named("chat_watcher")
177
178 conn, err := websocket.Accept(rw, r, nil)
179 if err != nil {
180 httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
181 Message: "Failed to open chat watch stream.",
182 Detail: err.Error(),
183 })
184 return
185 }
186
187 ctx, cancel := context.WithCancel(ctx)
188 defer cancel()
189
190 _ = conn.CloseRead(context.Background())
191
192 ctx, wsNetConn := codersdk.WebsocketNetConn(ctx, conn, websocket.MessageText)
193 defer wsNetConn.Close()
194
195 go httpapi.HeartbeatClose(ctx, logger, cancel, conn)
196
197 // The encoder is only written from the SubscribeWithErr callback,
198 // which delivers serially per subscription. Do not add a second
199 // write path without introducing synchronization.
200 encoder := json.NewEncoder(wsNetConn)
201
202 cancelSubscribe, err := api.Pubsub.SubscribeWithErr(pubsub.ChatWatchEventChannel(apiKey.UserID),
203 pubsub.HandleChatWatchEvent(
204 func(ctx context.Context, payload codersdk.ChatWatchEvent, err error) {
205 if err != nil {
206 logger.Error(ctx, "chat watch event subscription error", slog.Error(err))
207 return
208 }
209 if err := encoder.Encode(payload); err != nil {
210 logger.Debug(ctx, "failed to send chat watch event", slog.Error(err))
211 cancel()
212 return
213 }
214 },
215 ))
216 if err != nil {
217 logger.Error(ctx, "failed to subscribe to chat watch events", slog.Error(err))
218 _ = conn.Close(websocket.StatusInternalError, "Failed to subscribe to chat events.")
219 return
220 }
221 defer cancelSubscribe()
222
223 <-ctx.Done()
224}
225
226// EXPERIMENTAL: chatsByWorkspace returns a mapping of workspace ID to
227// the latest non-archived chat ID for each requested workspace.

Callers

nothing calls this directly

Calls 14

APIKeyFunction · 0.92
WriteFunction · 0.92
WebsocketNetConnFunction · 0.92
HeartbeatCloseFunction · 0.92
ChatWatchEventChannelFunction · 0.92
HandleChatWatchEventFunction · 0.92
NamedMethod · 0.80
EncodeMethod · 0.80
ContextMethod · 0.65
CloseMethod · 0.65
SubscribeWithErrMethod · 0.65
AcceptMethod · 0.45

Tested by

no test coverage detected