-
Notifications
You must be signed in to change notification settings - Fork 14
/
server.go
121 lines (99 loc) · 2.11 KB
/
server.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
119
120
121
package hitrix
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/latolukasz/orm"
"github.com/coretrix/hitrix/service"
"github.com/fatih/color"
"github.com/99designs/gqlgen/graphql"
)
type Hitrix struct {
ctx context.Context
cancel context.CancelFunc
done chan bool
exit chan int
}
func (h *Hitrix) RunServer(defaultPort uint, server graphql.ExecutableSchema, ginInitHandler GinInitHandler, gqlServerInitHandler GQLServerInitHandler) {
port := os.Getenv("PORT")
if port == "" {
port = fmt.Sprintf("%d", defaultPort)
}
srv := &http.Server{
Addr: ":" + port,
Handler: InitGin(server, ginInitHandler, gqlServerInitHandler),
}
h.preDeploy()
go func() {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
panic(err)
}
h.done <- true
}()
h.Await()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Println("server forced to shutdown")
}
}
func (h *Hitrix) RunAsyncOrmConsumer() *Hitrix {
ormService, has := service.DI().OrmEngine()
if !has {
panic("Orm is not registered")
}
go func() {
asyncConsumer := orm.NewBackgroundConsumer(ormService)
asyncConsumer.Digest(h.ctx)
}()
return h
}
func (h *Hitrix) preDeploy() {
app := service.DI().App()
if app.IsInTestMode() {
return
}
preDeployFlag := app.Flags.Bool("pre-deploy")
if !preDeployFlag {
return
}
ormService, has := service.DI().OrmEngine()
if !has {
return
}
alters := ormService.GetAlters()
hasAlters := false
for _, alter := range alters {
if alter.Safe {
color.Green("%s\n\n", alter.SQL)
} else {
color.Red("%s\n\n", alter.SQL)
}
hasAlters = true
}
if hasAlters {
os.Exit(1)
}
os.Exit(0)
}
func (h *Hitrix) Await() {
termChan := make(chan os.Signal, 1)
signal.Notify(termChan, syscall.SIGINT, syscall.SIGTERM)
select {
case code := <-h.exit:
h.cancel()
os.Exit(code)
case <-h.done:
h.cancel()
case <-termChan:
log.Println("TERMINATING")
h.cancel()
time.Sleep(time.Millisecond * 300)
log.Println("TERMINATED")
}
}