Skip to content

Commit

Permalink
fixed data race
Browse files Browse the repository at this point in the history
  • Loading branch information
aricart committed Oct 19, 2022
1 parent 680718f commit bba377a
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions service.go
Expand Up @@ -18,6 +18,7 @@ import (
"errors"
"fmt"
"strings"
"sync"
"time"
)

Expand Down Expand Up @@ -131,6 +132,7 @@ func (s ServiceVerb) String() string {

// ServiceImpl is the internal implementation of a Service
type ServiceImpl struct {
sync.Mutex
ServiceConfig
// subs
reqSub *Subscription
Expand Down Expand Up @@ -165,10 +167,12 @@ func (svc *ServiceImpl) _addInternalHandler(nc *Conn, verb ServiceVerb, kind str

svc.internal[name], err = nc.Subscribe(subj, func(msg *Msg) {
start := time.Now()
stats := svc.statuses[name]
defer func() {
svc.Lock()
stats := svc.statuses[name]
stats.NumRequests++
stats.TotalLatency += time.Since(start)
svc.Unlock()
}()
handler(msg)
})
Expand Down Expand Up @@ -261,14 +265,19 @@ func (nc *Conn) AddService(config ServiceConfig) (Service, error) {
// reqHandler itself
func (svc *ServiceImpl) reqHandler(req *Msg) {
start := time.Now()
stats := svc.statuses[""]
defer func() {
svc.Lock()
stats := svc.statuses[""]
stats.NumRequests++
stats.TotalLatency += time.Since(start)
svc.Unlock()
}()

if err := svc.ServiceConfig.Endpoint.Handler(svc, req); err != nil {
svc.Lock()
stats := svc.statuses[""]
stats.NumErrors++
svc.Unlock()
req.Sub.mu.Lock()
nc := req.Sub.conn
req.Sub.mu.Unlock()
Expand Down Expand Up @@ -310,6 +319,10 @@ func (svc *ServiceImpl) Version() string {
}

func (svc *ServiceImpl) Stats() ServiceStats {
svc.Lock()
defer func() {
svc.Unlock()
}()
if svc.ServiceConfig.StatusHandler != nil {
stats := svc.statuses[""]
stats.Data = svc.ServiceConfig.StatusHandler(svc.Endpoint)
Expand Down

0 comments on commit bba377a

Please sign in to comment.