-
Notifications
You must be signed in to change notification settings - Fork 2
/
application.go
207 lines (160 loc) · 4.67 KB
/
application.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
package application
import (
"context"
"errors"
"fmt"
"net"
"net/http"
"strings"
"sync"
"time"
"github.com/dgraph-io/badger/v4"
"github.com/ogen-go/ogen/middleware"
"go.uber.org/multierr"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"github.com/derfenix/webarchive/adapters/repository"
"github.com/derfenix/webarchive/adapters/processors"
badgerRepo "github.com/derfenix/webarchive/adapters/repository/badger"
"github.com/derfenix/webarchive/api/openapi"
"github.com/derfenix/webarchive/config"
"github.com/derfenix/webarchive/entity"
"github.com/derfenix/webarchive/ports/rest"
)
func NewApplication(cfg config.Config) (Application, error) {
log, err := newLogger(cfg.Logging)
if err != nil {
return Application{}, fmt.Errorf("new logger: %w", err)
}
db, err := repository.NewBadger(cfg.DB.Path, log.Named("db"))
if err != nil {
return Application{}, fmt.Errorf("new badger: %w", err)
}
pageRepo, err := badgerRepo.NewPage(db)
if err != nil {
return Application{}, fmt.Errorf("new page repo: %w", err)
}
processor, err := processors.NewProcessors(cfg, log.Named("processor"))
if err != nil {
return Application{}, fmt.Errorf("new processors: %w", err)
}
workerCh := make(chan *entity.Page)
worker := entity.NewWorker(workerCh, pageRepo, processor, log.Named("worker"))
server, err := openapi.NewServer(
rest.NewService(pageRepo, workerCh, processor),
openapi.WithPathPrefix("/api/v1"),
openapi.WithMiddleware(
func(r middleware.Request, next middleware.Next) (middleware.Response, error) {
start := time.Now()
log := log.With(
zap.String("operation_id", r.OperationID),
zap.String("uri", r.Raw.RequestURI),
)
var response middleware.Response
var reqErr error
response, reqErr = next(r)
log.Debug("request completed", zap.Duration("duration", time.Since(start)), zap.Error(err))
return response, reqErr
},
),
)
if err != nil {
return Application{}, fmt.Errorf("new rest server: %w", err)
}
var httpHandler http.Handler = server
if cfg.UI.Enabled {
ui := rest.NewUI(cfg.UI)
httpHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/api/") {
server.ServeHTTP(w, r)
return
}
ui.ServeHTTP(w, r)
})
}
httpServer := http.Server{
Addr: cfg.API.Address,
Handler: httpHandler,
ReadTimeout: time.Second * 15,
ReadHeaderTimeout: time.Second * 5,
IdleTimeout: time.Second * 30,
MaxHeaderBytes: 1024 * 2,
}
return Application{
cfg: cfg,
log: log,
db: db,
processor: processor,
httpServer: &httpServer,
worker: worker,
pageRepo: pageRepo,
}, nil
}
type Application struct {
cfg config.Config
log *zap.Logger
db *badger.DB
processor entity.Processor
httpServer *http.Server
worker *entity.Worker
pageRepo *badgerRepo.Page
}
func (a *Application) Log() *zap.Logger {
return a.log
}
func (a *Application) Start(ctx context.Context, wg *sync.WaitGroup) error {
wg.Add(3)
a.httpServer.BaseContext = func(net.Listener) context.Context {
return ctx
}
go a.worker.Start(ctx, wg)
go func() {
defer wg.Done()
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
if err := a.httpServer.Shutdown(shutdownCtx); err != nil {
a.log.Warn("http graceful shutdown failed", zap.Error(err))
}
}()
go func() {
defer wg.Done()
a.log.Info("starting http server", zap.String("address", a.httpServer.Addr))
if err := a.httpServer.ListenAndServe(); err != nil {
if !errors.Is(err, http.ErrServerClosed) {
a.log.Error("http serve error", zap.Error(err))
}
a.log.Info("http server stopped")
}
}()
return nil
}
func (a *Application) Stop() error {
var errs error
if err := a.db.Sync(); err != nil {
errs = multierr.Append(errs, fmt.Errorf("sync db: %w", err))
}
if err := repository.Backup(a.db, repository.BackupStop); err != nil {
errs = multierr.Append(errs, fmt.Errorf("backup on stop: %w", err))
}
if err := a.db.Close(); err != nil {
errs = multierr.Append(errs, fmt.Errorf("close db: %w", err))
}
return errs
}
func newLogger(cfg config.Logging) (*zap.Logger, error) {
logCfg := zap.NewProductionConfig()
logCfg.EncoderConfig.EncodeTime = zapcore.RFC3339TimeEncoder
logCfg.EncoderConfig.EncodeDuration = zapcore.NanosDurationEncoder
logCfg.DisableCaller = true
logCfg.DisableStacktrace = true
logCfg.Level = zap.NewAtomicLevelAt(zapcore.InfoLevel)
if cfg.Debug {
logCfg.Level = zap.NewAtomicLevelAt(zapcore.DebugLevel)
}
log, err := logCfg.Build()
if err != nil {
return nil, fmt.Errorf("build logger: %w", err)
}
return log, nil
}