Skip to content

Commit

Permalink
feat: better logging using zap for traces purposed
Browse files Browse the repository at this point in the history
  • Loading branch information
elskow committed Oct 20, 2024
1 parent 08c98a4 commit 92c719b
Show file tree
Hide file tree
Showing 10 changed files with 247 additions and 117 deletions.
17 changes: 10 additions & 7 deletions editor-cp/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,25 @@ module github.com/elskow/codepair/editor-cp
go 1.23.0

require (
github.com/gofiber/contrib/fiberzap/v2 v2.1.4
github.com/gofiber/fiber/v2 v2.52.5
github.com/gofiber/websocket/v2 v2.2.1
go.uber.org/zap v1.27.0
)

require (
github.com/andybalholm/brotli v1.0.5 // indirect
github.com/andybalholm/brotli v1.1.1 // indirect
github.com/fasthttp/websocket v1.5.3 // indirect
github.com/google/uuid v1.5.0 // indirect
github.com/klauspost/compress v1.17.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/klauspost/compress v1.17.11 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-runewidth v0.0.15 // indirect
github.com/rivo/uniseg v0.2.0 // indirect
github.com/mattn/go-runewidth v0.0.16 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/savsgio/gotils v0.0.0-20230208104028-c358bd845dee // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasthttp v1.51.0 // indirect
github.com/valyala/fasthttp v1.56.0 // indirect
github.com/valyala/tcplisten v1.0.0 // indirect
golang.org/x/sys v0.15.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/sys v0.26.0 // indirect
)
45 changes: 32 additions & 13 deletions editor-cp/go.sum
Original file line number Diff line number Diff line change
@@ -1,33 +1,52 @@
github.com/andybalholm/brotli v1.0.5 h1:8uQZIdzKmjc/iuPu7O2ioW48L81FgatrcpfFmiq/cCs=
github.com/andybalholm/brotli v1.0.5/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA=
github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fasthttp/websocket v1.5.3 h1:TPpQuLwJYfd4LJPXvHDYPMFWbLjsT91n3GpWtCQtdek=
github.com/fasthttp/websocket v1.5.3/go.mod h1:46gg/UBmTU1kUaTcwQXpUxtRwG2PvIZYeA8oL6vF3Fs=
github.com/gofiber/contrib/fiberzap/v2 v2.1.4 h1:GCtCQnT4Cr9az4qab2Ozmqsomkxm4Ei86MfKk/1p5+0=
github.com/gofiber/contrib/fiberzap/v2 v2.1.4/go.mod h1:PkdXgUzw+oj4m6ksfKJ0Hs3H7iPhwvhfI4b2LSA9hhA=
github.com/gofiber/fiber/v2 v2.52.5 h1:tWoP1MJQjGEe4GB5TUGOi7P2E0ZMMRx5ZTG4rT+yGMo=
github.com/gofiber/fiber/v2 v2.52.5/go.mod h1:KEOE+cXMhXG0zHc9d8+E38hoX+ZN7bhOtgeF2oT6jrQ=
github.com/gofiber/websocket/v2 v2.2.1 h1:C9cjxvloojayOp9AovmpQrk8VqvVnT8Oao3+IUygH7w=
github.com/gofiber/websocket/v2 v2.2.1/go.mod h1:Ao/+nyNnX5u/hIFPuHl28a+NIkrqK7PRimyKaj4JxVU=
github.com/google/uuid v1.5.0 h1:1p67kYwdtXjb0gL0BPiP1Av9wiZPo5A8z2cWkTZ+eyU=
github.com/google/uuid v1.5.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/klauspost/compress v1.17.0 h1:Rnbp4K9EjcDuVuHtd0dgA4qNuv9yKDYKK1ulpJwgrqM=
github.com/klauspost/compress v1.17.0/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc=
github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=
github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/savsgio/gotils v0.0.0-20230208104028-c358bd845dee h1:8Iv5m6xEo1NR1AvpV+7XmhI4r39LGNzwUL4YpMuL5vk=
github.com/savsgio/gotils v0.0.0-20230208104028-c358bd845dee/go.mod h1:qwtSXrKuJh/zsFQ12yEE89xfCrGKK63Rr7ctU/uCo4g=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasthttp v1.51.0 h1:8b30A5JlZ6C7AS81RsWjYMQmrZG6feChmgAolCl1SqA=
github.com/valyala/fasthttp v1.51.0/go.mod h1:oI2XroL+lI7vdXyYoQk03bXBThfFl2cVdIA3Xl7cH8g=
github.com/valyala/fasthttp v1.56.0 h1:bEZdJev/6LCBlpdORfrLu/WOZXXxvrUQSiyniuaoW8U=
github.com/valyala/fasthttp v1.56.0/go.mod h1:sReBt3XZVnudxuLOx4J/fMrJVorWRiWY2koQKgABiVI=
github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8=
github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc=
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc=
golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo=
golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
31 changes: 24 additions & 7 deletions editor-cp/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,50 +2,67 @@ package main

import (
"context"
"log"
"os"
"os/signal"
"syscall"
"time"

"github.com/gofiber/contrib/fiberzap/v2"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/compress"
"github.com/gofiber/fiber/v2/middleware/healthcheck"
"github.com/gofiber/fiber/v2/middleware/recover"
"github.com/gofiber/fiber/v2/middleware/requestid"
"go.uber.org/zap"
)

const (
address = ":8080"
)

func main() {
logger, err := zap.NewProduction()
if err != nil {
panic(err)
}
defer logger.Sync()

app := fiber.New(fiber.Config{AppName: "PeerEditor Modules"})

app.Use(fiberzap.New(fiberzap.Config{
Logger: logger,
}))

app.Use(recover.New())
app.Use(requestid.New())
app.Use(healthcheck.New())
app.Use(compress.New(compress.Config{Level: compress.LevelBestSpeed}))

server := NewServer(app)
server := NewServer(app, logger)
server.setupRoutes()

stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)

go func() {
if err := app.Listen(address); err != nil {
log.Fatalf("Failed to start server: %v", err)
logger.Fatal("Failed to start server", zap.Error(err))
}
}()

log.Println("Server started on", address)
logger.Info("Server started", zap.String("address", address))

<-stop

log.Println("Shutting down server...")
logger.Info("Shutting down server...")

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

if err := server.Shutdown(ctx); err != nil {
log.Fatalf("Server forced to shutdown: %v", err)
logger.Error("Server forced to shutdown", zap.Error(err))
}

<-ctx.Done()
log.Println("Server stopped gracefully")
logger.Info("Server stopped gracefully")
}
46 changes: 38 additions & 8 deletions editor-cp/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,26 @@ package main

import (
"context"
"log"
"sync"

"github.com/gofiber/fiber/v2"
"github.com/gofiber/websocket/v2"
"go.uber.org/zap"
)

type Server struct {
app *fiber.App
rooms map[string]*Room
roomsMutex sync.RWMutex
broadcast chan RoomMessage
logger *zap.Logger
}

func (s *Server) getLogger(ctx context.Context) *zap.Logger {
if requestID, ok := ctx.Value("requestID").(string); ok {
return s.logger.With(zap.String("requestID", requestID))
}
return s.logger
}

type Room struct {
Expand Down Expand Up @@ -41,11 +49,12 @@ type Cursor struct {
Column int `json:"column"`
}

func NewServer(app *fiber.App) *Server {
func NewServer(app *fiber.App, logger *zap.Logger) *Server {
return &Server{
app: app,
rooms: make(map[string]*Room),
broadcast: make(chan RoomMessage, 20),
logger: logger,
}
}

Expand All @@ -57,9 +66,12 @@ func (s *Server) setupRoutes() {
func (s *Server) handleWebSocket(c *websocket.Conn) {
defer c.Close()

ctx := context.WithValue(context.Background(), "requestID", c.Params("requestId"))
logger := s.getLogger(ctx)

roomID := c.Params("roomId")
if roomID == "" {
log.Println("Room ID is required")
logger.Warn("Empty room ID")
return
}

Expand All @@ -76,16 +88,20 @@ func (s *Server) handleWebSocket(c *websocket.Conn) {
room.clients[c] = true
room.clientsMutex.Unlock()

logger.Info("Client connected", zap.String("roomID", roomID))

if room.currentCode != "" {
syncMessage := Message{
Type: "sync",
Code: room.currentCode,
Language: room.language,
}
c.WriteJSON(syncMessage)
if err := c.WriteJSON(syncMessage); err != nil {
logger.Error("Failed to send sync message", zap.Error(err))
}
}

ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(ctx)
defer cancel()

go s.handleIncomingMessages(ctx, c, roomID)
Expand All @@ -99,11 +115,16 @@ func (s *Server) handleWebSocket(c *websocket.Conn) {
s.roomsMutex.Lock()
if len(room.clients) == 0 {
delete(s.rooms, roomID)
logger.Info("Room closed", zap.String("roomID", roomID))
}
s.roomsMutex.Unlock()

logger.Info("Client disconnected", zap.String("roomID", roomID))
}

func (s *Server) handleIncomingMessages(ctx context.Context, c *websocket.Conn, roomID string) {
logger := s.getLogger(ctx)

for {
select {
case <-ctx.Done():
Expand All @@ -113,7 +134,7 @@ func (s *Server) handleIncomingMessages(ctx context.Context, c *websocket.Conn,
err := c.ReadJSON(&msg)
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
log.Printf("error: %v", err)
logger.Error("Unexpected close error", zap.Error(err))
}
return
}
Expand All @@ -125,6 +146,7 @@ func (s *Server) handleIncomingMessages(ctx context.Context, c *websocket.Conn,

room.currentCode = msg.Code
room.language = msg.Language
logger.Debug("Code updated", zap.String("roomID", roomID), zap.String("language", msg.Language))
}

s.broadcast <- RoomMessage{RoomID: roomID, Message: msg}
Expand All @@ -134,6 +156,9 @@ func (s *Server) handleIncomingMessages(ctx context.Context, c *websocket.Conn,

func (s *Server) handleMessages() {
for roomMsg := range s.broadcast {
ctx := context.Background()
logger := s.getLogger(ctx)

s.roomsMutex.RLock()
room, exists := s.rooms[roomMsg.RoomID]
s.roomsMutex.RUnlock()
Expand All @@ -147,7 +172,9 @@ func (s *Server) handleMessages() {
go func(client *websocket.Conn) {
err := client.WriteJSON(roomMsg.Message)
if err != nil {
log.Printf("error: %v", err)
logger.Error("Failed to send message to client",
zap.Error(err),
zap.String("roomID", roomMsg.RoomID))
client.Close()
room.clientsMutex.Lock()
delete(room.clients, client)
Expand All @@ -160,15 +187,18 @@ func (s *Server) handleMessages() {
}

func (s *Server) Shutdown(ctx context.Context) error {
logger := s.getLogger(ctx)

s.roomsMutex.Lock()
defer s.roomsMutex.Unlock()

for _, room := range s.rooms {
for roomID, room := range s.rooms {
room.clientsMutex.Lock()
for client := range room.clients {
client.Close()
}
room.clientsMutex.Unlock()
logger.Info("Room closed during shutdown", zap.String("roomID", roomID))
}

shutdownErr := make(chan error, 1)
Expand Down
1 change: 0 additions & 1 deletion gateway/docker-compose.yaml
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
version: "3"
services:
nginx:
image: nginx:1.21-alpine
Expand Down
19 changes: 11 additions & 8 deletions videochat-cp/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,21 @@ module github.com/elskow/codepair/videochat-cp
go 1.23.1

require (
github.com/gofiber/contrib/fiberzap/v2 v2.1.4
github.com/gofiber/fiber/v2 v2.52.5
github.com/gofiber/websocket/v2 v2.2.1
github.com/pion/webrtc/v4 v4.0.0-beta.29
go.uber.org/zap v1.27.0
)

require (
github.com/andybalholm/brotli v1.0.5 // indirect
github.com/andybalholm/brotli v1.1.1 // indirect
github.com/fasthttp/websocket v1.5.3 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/klauspost/compress v1.17.0 // indirect
github.com/klauspost/compress v1.17.11 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-runewidth v0.0.15 // indirect
github.com/mattn/go-runewidth v0.0.16 // indirect
github.com/pion/datachannel v1.5.9 // indirect
github.com/pion/dtls/v3 v3.0.1 // indirect
github.com/pion/ice/v4 v4.0.1 // indirect
Expand All @@ -31,13 +33,14 @@ require (
github.com/pion/stun/v3 v3.0.0 // indirect
github.com/pion/transport/v3 v3.0.7 // indirect
github.com/pion/turn/v4 v4.0.0 // indirect
github.com/rivo/uniseg v0.2.0 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/savsgio/gotils v0.0.0-20230208104028-c358bd845dee // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasthttp v1.51.0 // indirect
github.com/valyala/fasthttp v1.56.0 // indirect
github.com/valyala/tcplisten v1.0.0 // indirect
github.com/wlynxg/anet v0.0.3 // indirect
golang.org/x/crypto v0.26.0 // indirect
golang.org/x/net v0.27.0 // indirect
golang.org/x/sys v0.24.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/crypto v0.27.0 // indirect
golang.org/x/net v0.29.0 // indirect
golang.org/x/sys v0.26.0 // indirect
)
Loading

0 comments on commit 92c719b

Please sign in to comment.