-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathbark.go
More file actions
261 lines (241 loc) · 6.33 KB
/
Copy pathbark.go
File metadata and controls
261 lines (241 loc) · 6.33 KB
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
// Copyright 2026 Blink Labs Software
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package bark
import (
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"sync"
"time"
"connectrpc.com/connect"
"connectrpc.com/grpchealth"
"connectrpc.com/grpcreflect"
archiveconnect "github.com/blinklabs-io/bark/proto/v1alpha1/archive/archivev1alpha1connect"
"github.com/blinklabs-io/dingo/database"
"github.com/blinklabs-io/dingo/internal/httpcors"
"github.com/blinklabs-io/dingo/internal/tlsutil"
)
type Bark struct {
mu sync.Mutex // protects server
server *http.Server
config BarkConfig
}
type BarkConfig struct {
Logger *slog.Logger
DB *database.Database
TlsCertFilePath string
TlsKeyFilePath string
Host string
Port uint
// CORSAllowedOrigins configures Access-Control-Allow-Origin.
// Empty disables CORS.
CORSAllowedOrigins []string
}
func NewBark(cfg BarkConfig) (*Bark, error) {
if cfg.DB == nil {
return nil, errors.New("bark: db is required")
}
if cfg.Logger == nil {
cfg.Logger = slog.New(slog.NewJSONHandler(io.Discard, nil))
}
if cfg.Host == "" {
cfg.Host = "0.0.0.0"
}
if cfg.Port == 0 {
cfg.Port = 9091
}
return &Bark{
config: cfg,
}, nil
}
func (b *Bark) Start(ctx context.Context) error {
b.mu.Lock()
if b.server != nil {
b.mu.Unlock()
return errors.New("server already started")
}
mux := http.NewServeMux()
compress1KB := connect.WithCompressMinBytes(1024)
archivePath, archiveHandler := archiveconnect.NewArchiveServiceHandler(
&archiveServiceHandler{bark: b},
compress1KB,
)
mux.Handle(archivePath, archiveHandler)
mux.Handle(
grpchealth.NewHandler(
grpchealth.NewStaticChecker(archiveconnect.ArchiveServiceName),
compress1KB,
),
)
mux.Handle(
grpcreflect.NewHandlerV1(
grpcreflect.NewStaticReflector(
archiveconnect.ArchiveServiceName,
),
compress1KB,
),
)
handler := httpcors.Handler(
mux,
httpcors.Config{
AllowedOrigins: b.config.CORSAllowedOrigins,
},
)
var server *http.Server
if b.config.TlsCertFilePath != "" && b.config.TlsKeyFilePath != "" {
b.config.Logger.Info(
fmt.Sprintf("starting bark gRPC TLS listener on %s:%d",
b.config.Host,
b.config.Port,
),
)
server = &http.Server{
Addr: fmt.Sprintf(
"%s:%d",
b.config.Host,
b.config.Port,
),
Handler: handler,
ReadHeaderTimeout: 60 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 120 * time.Second,
}
} else {
b.config.Logger.Info(
fmt.Sprintf("starting bark gRPC listener on %s:%d",
b.config.Host,
b.config.Port,
),
)
server = &http.Server{
Addr: fmt.Sprintf(
"%s:%d",
b.config.Host,
b.config.Port,
),
Handler: handler,
Protocols: unencryptedHTTP2Protocols(),
ReadHeaderTimeout: 60 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 120 * time.Second,
}
}
b.server = server
b.mu.Unlock()
if err := b.startServer(server); err != nil {
b.mu.Lock()
b.server = nil
b.mu.Unlock()
return err
}
go func() { //nolint:gosec // G118: goroutine intentionally outlives ctx to perform graceful shutdown
<-ctx.Done()
b.mu.Lock()
if b.server == server {
b.config.Logger.Debug(
"context cancelled, shutting down bark gRPC server",
)
//nolint:contextcheck //shutdownCtx is intentionally created from background to allow shutdown to complete even if ctx is cancelled
shutdownCtx, cancel := context.WithTimeout(
context.Background(),
30*time.Second,
)
defer cancel()
if err := server.Shutdown(shutdownCtx); err != nil { //nolint:contextcheck //shutdownCtx is intentionally created from background to allow shutdown to complete even if ctx is cancelled
b.config.Logger.Error(
"failed to shutdown bark gRPC server on context cancellation",
"error",
err,
)
}
b.server = nil
}
b.mu.Unlock()
}()
return nil
}
func unencryptedHTTP2Protocols() *http.Protocols {
protocols := &http.Protocols{}
protocols.SetHTTP1(true)
protocols.SetUnencryptedHTTP2(true)
return protocols
}
// startServer starts the HTTP server with deterministic error
// detection. It validates TLS configuration, binds the listening
// socket and pre-loads any TLS keypair synchronously so port and
// certificate errors surface before returning, then serves in a
// background goroutine.
func (b *Bark) startServer(server *http.Server) error {
if (b.config.TlsCertFilePath != "") != (b.config.TlsKeyFilePath != "") {
return errors.New(
"failed to start bark gRPC server: both tls cert and key must be specified",
)
}
useTLS := b.config.TlsCertFilePath != "" && b.config.TlsKeyFilePath != ""
serverType := "non-TLS"
if useTLS {
serverType = "TLS"
if _, err := tls.LoadX509KeyPair(
b.config.TlsCertFilePath,
b.config.TlsKeyFilePath,
); err != nil {
return fmt.Errorf(
"failed to load TLS keypair for bark gRPC %s server: %w",
serverType, err,
)
}
server.TLSConfig = tlsutil.ServerConfig(server.TLSConfig)
}
ln, err := net.Listen("tcp", server.Addr)
if err != nil {
return fmt.Errorf("failed to start bark gRPC %s server: %w",
serverType, err)
}
go func() {
var serveErr error
if useTLS {
serveErr = server.ServeTLS(
ln,
b.config.TlsCertFilePath,
b.config.TlsKeyFilePath,
)
} else {
serveErr = server.Serve(ln)
}
if serveErr != nil && !errors.Is(serveErr, http.ErrServerClosed) {
b.config.Logger.Error(
"bark gRPC server error",
"error", serveErr,
)
}
}()
return nil
}
func (b *Bark) Stop(ctx context.Context) error {
b.mu.Lock()
defer b.mu.Unlock()
if b.server != nil {
b.config.Logger.Debug("shutting down bark gRPC server")
if err := b.server.Shutdown(ctx); err != nil {
return fmt.Errorf("failed to shutdown bark gRPC server: %w", err)
}
b.server = nil
}
return nil
}