2023-09-07 21:23:51 -06:00
|
|
|
package handler
|
|
|
|
|
|
|
|
import (
|
2023-09-20 14:57:12 -06:00
|
|
|
"fmt"
|
2023-09-07 21:23:51 -06:00
|
|
|
"github.com/fastenhealth/fasten-onprem/backend/pkg"
|
2023-09-20 14:57:12 -06:00
|
|
|
"github.com/fastenhealth/fasten-onprem/backend/pkg/database"
|
2023-09-09 09:24:25 -06:00
|
|
|
"github.com/fastenhealth/fasten-onprem/backend/pkg/event_bus"
|
2023-09-07 21:23:51 -06:00
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"io"
|
|
|
|
)
|
|
|
|
|
|
|
|
// SSEStream is a handler for the server sent event stream (notifications from background processes)
|
|
|
|
// see: https://github.com/gin-gonic/examples/blob/master/server-sent-event/main.go
|
|
|
|
// see: https://stackoverflow.com/questions/66327142/selectively-send-event-to-particular-clients
|
|
|
|
//
|
|
|
|
// test using:
|
|
|
|
// curl -N -H "Authorization: Bearer xxxxx" http://localhost:9090/api/secure/sse/stream
|
2023-09-20 14:57:12 -06:00
|
|
|
|
|
|
|
func SSEEventBusServerHandler(eventBus event_bus.Interface) gin.HandlerFunc {
|
|
|
|
|
|
|
|
return func(c *gin.Context) {
|
|
|
|
//get a reference to the current user
|
|
|
|
databaseRepo := c.MustGet(pkg.ContextKeyTypeDatabase).(database.DatabaseRepository)
|
|
|
|
|
|
|
|
foundUser, err := databaseRepo.GetCurrentUser(c)
|
|
|
|
if err != nil || foundUser == nil {
|
|
|
|
c.Error(fmt.Errorf("could not find user"))
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Initialize client channel
|
|
|
|
clientListener := event_bus.EventBusListener{
|
|
|
|
ResponseChan: make(chan string),
|
|
|
|
UserID: foundUser.ID.String(),
|
2023-09-07 21:23:51 -06:00
|
|
|
}
|
2023-09-20 14:57:12 -06:00
|
|
|
|
|
|
|
// Send new connection to event server
|
|
|
|
eventBus.AddListener(&clientListener)
|
|
|
|
|
|
|
|
defer func() {
|
|
|
|
// Send closed connection to event server
|
|
|
|
eventBus.RemoveListener(&clientListener)
|
|
|
|
}()
|
|
|
|
|
|
|
|
c.Stream(func(w io.Writer) bool {
|
|
|
|
// Stream message to client from message channel
|
|
|
|
if msg, ok := <-clientListener.ResponseChan; ok {
|
|
|
|
c.SSEvent("message", msg)
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
})
|
|
|
|
|
|
|
|
}
|
2023-09-07 21:23:51 -06:00
|
|
|
}
|