/
service.go
118 lines (96 loc) · 2.63 KB
/
service.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package master
import (
"context"
"net/http"
"time"
"github.com/edgestore/edgestore/association"
"github.com/edgestore/edgestore/entity"
"github.com/edgestore/edgestore/internal/eventstore"
"github.com/edgestore/edgestore/internal/eventstore/pgstore"
"github.com/edgestore/edgestore/internal/guid"
"github.com/edgestore/edgestore/internal/server"
"github.com/gin-gonic/gin"
"github.com/redis/go-redis/v9"
"github.com/sirupsen/logrus"
)
// CacheKeyPrefix is used to define caching keys.
const CacheKeyPrefix = "everstore"
type Service interface{}
type service struct {
association *association.Service
cache *redis.Client
cfg Config
entity *entity.Service
guid *guid.Generator
logger logrus.FieldLogger
run func() error
}
func New(cfg Config) *service {
if cfg.Server.LoggerLevel != "debug" {
gin.SetMode("release")
}
// Logger
logger := server.NewLogger(cfg.Server.LoggerLevel, cfg.Server.LoggerFormat)
// Event Store
var store eventstore.Store
if cfg.Database == nil {
store = eventstore.NewInMemory(logger)
} else {
store = pgstore.New(cfg.Database, logger)
}
cache := redis.NewClient(cfg.Cache)
// Data Store Service
assocSvc := association.New(&association.Config{
Cache: cache,
CacheKeyPrefix: CacheKeyPrefix,
Store: store,
Logger: logger,
})
entitySvc := entity.New(&entity.Config{
Cache: cache,
CacheKeyPrefix: CacheKeyPrefix,
Store: store,
Logger: logger,
})
guidSvc := guid.New(guid.Settings{
StartTime: time.Now(),
MachineID: func() (uint16, error) { return cfg.MachineID, nil },
})
// Main Service
svc := &service{
association: assocSvc,
cache: cache,
cfg: cfg,
entity: entitySvc,
guid: guidSvc,
logger: logger.WithField("component", "API"),
}
srv := server.New(cfg.Server, logger)
srv.HTTPServer = server.NewHTTPServer(cfg.Server, svc.HTTPHandler())
svc.run = srv.Run
return svc
}
func (s *service) Run() error {
s.logger.Info("Edgestore: Starting Master")
if s.cache != nil {
if _, err := s.cache.Ping(context.Background()).Result(); err != nil {
s.logger.Errorf("unable to connect to Redis: %v", err)
} else {
s.logger.Infof("Connected to Redis at %v", s.cfg.Cache.Addr)
}
}
return s.run()
}
func (s *service) Shutdown() {
s.logger.Info("Edgestore: Stopping Master")
if s.cache != nil {
if _, err := s.cache.Shutdown(context.Background()).Result(); err != nil {
s.logger.Error(err)
}
}
}
func (s *service) RootHandler(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{
"message": "Edgestore: Distributed Data Store (Master)",
})
}