API and Database Deployment Update
This commit is contained in:
@@ -1,27 +1,21 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
var upgrader = websocket.Upgrader{
|
||||
CheckOrigin: func(r *http.Request) bool { return true },
|
||||
}
|
||||
|
||||
type LogHub struct {
|
||||
mu sync.Mutex
|
||||
streams map[string][]chan []byte
|
||||
}
|
||||
|
||||
var Hub = &LogHub{
|
||||
streams: make(map[string][]chan []byte),
|
||||
}
|
||||
|
||||
func (h *LogHub) Broadcast(deploymentID string, p []byte) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
@@ -34,7 +28,6 @@ func (h *LogHub) Broadcast(deploymentID string, p []byte) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (h *LogHub) Subscribe(deploymentID string) chan []byte {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
@@ -42,7 +35,6 @@ func (h *LogHub) Subscribe(deploymentID string) chan []byte {
|
||||
h.streams[deploymentID] = append(h.streams[deploymentID], ch)
|
||||
return ch
|
||||
}
|
||||
|
||||
func (h *LogHub) Unsubscribe(deploymentID string, ch chan []byte) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
@@ -59,34 +51,28 @@ func (h *LogHub) Unsubscribe(deploymentID string, ch chan []byte) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type StreamWriter struct {
|
||||
DeploymentID string
|
||||
}
|
||||
|
||||
func (w *StreamWriter) Write(p []byte) (n int, err error) {
|
||||
c := make([]byte, len(p))
|
||||
copy(c, p)
|
||||
Hub.Broadcast(w.DeploymentID, c)
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func (h *Handler) streamDeploymentLogs(c *gin.Context) {
|
||||
deploymentID := c.Param("id")
|
||||
if deploymentID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid ID"})
|
||||
return
|
||||
}
|
||||
|
||||
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
logChan := Hub.Subscribe(deploymentID)
|
||||
defer Hub.Unsubscribe(deploymentID, logChan)
|
||||
|
||||
go func() {
|
||||
for {
|
||||
if _, _, err := conn.NextReader(); err != nil {
|
||||
@@ -95,7 +81,6 @@ func (h *Handler) streamDeploymentLogs(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
for logChunk := range logChan {
|
||||
conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
|
||||
if err := conn.WriteMessage(websocket.TextMessage, logChunk); err != nil {
|
||||
@@ -103,7 +88,6 @@ func (h *Handler) streamDeploymentLogs(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) RegisterStreamRoutes(r *gin.Engine) {
|
||||
r.GET("/api/deployments/:id/logs/stream", h.streamDeploymentLogs)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user