-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.tmpl
361 lines (307 loc) · 11.4 KB
/
server.tmpl
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
// Code generated by GripMock. DO NOT EDIT.
//
// This file is generated by GripMock, a tool for generating gRPC mock servers.
// GripMock is a mock server for gRPC services. It's using a .proto file to generate implementation of gRPC service for you.
// You can use GripMock for setting up end-to-end testing or as a dummy server in a software development phase.
// The server implementation is in GoLang but the client can be any programming language that support gRPC.
//
// See https://github.com/bavix/gripmock for more information.
package main
import (
"context"
"time"
"slices"
"fmt"
"log"
"net"
"net/http"
"encoding/json"
jsonpb "google.golang.org/protobuf/encoding/protojson"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/reflection"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/grpc/health"
healthgrpc "google.golang.org/grpc/health/grpc_health_v1"
_ "google.golang.org/grpc/encoding/gzip"
"github.com/gripmock/environment"
"github.com/rs/zerolog"
"github.com/bavix/gripmock/pkg/grpccontext"
sdk "github.com/bavix/gripmock-sdk-go"
"github.com/bavix/gripmock/pkg/zlogger"
)
{{ range $package, $alias := .Dependencies }}
import {{$alias}} "{{$package}}"
{{end}}
{{ range .Services }}
{{ template "services" . }}
{{ end }}
func main() {
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
defer cancel()
config, err := environment.New()
if err != nil {
log.Fatal(err)
}
level, err := zerolog.ParseLevel(config.LogLevel)
if err != nil {
log.Fatal(err)
}
ctx = zlogger.Logger(ctx, level)
logger := zerolog.Ctx(ctx)
lis, err := net.Listen(config.GRPCNetwork, config.GRPCAddr)
if err != nil {
logger.Fatal().Err(err).Msg("failed to listen")
}
s := grpc.NewServer(
grpc.UnaryInterceptor(grpccontext.UnaryInterceptor(logger)),
grpc.StreamInterceptor(grpccontext.StreamInterceptor(logger)),
)
healthcheck := health.NewServer()
healthcheck.SetServingStatus("gripmock", healthgrpc.HealthCheckResponse_NOT_SERVING)
{{ range .Services }}
{{ template "register_services" . }}
{{ end }}
healthgrpc.RegisterHealthServer(s, healthcheck)
reflection.Register(s)
logger.Info().
Str("addr", config.GRPCAddr).
Str("network", config.GRPCNetwork).
Msg("Serving gRPC")
// Health check goroutine to wait for the HTTP server to become ready.
// Once the HTTP server is ready, it sets the gRPC server to SERVING state.
go func() {
// Create a new client to interact with the HTTP server API.
api, err := sdk.NewClientWithResponses(
fmt.Sprintf("http://%s/api", config.HTTPAddr),
sdk.WithHTTPClient(http.DefaultClient),
)
if err != nil {
return
}
// Create a context with a timeout of 120 seconds.
ctx, cancel := context.WithTimeout(ctx, 120*time.Second)
defer cancel()
// Create a ticker to periodically check the readiness of the HTTP server.
tick := time.NewTicker(250 * time.Millisecond)
defer tick.Stop()
for {
select {
// Check if the context is done.
case <-ctx.Done():
return
// Check if the ticker has fired.
case <-tick.C:
// Call the Readiness API on the HTTP server.
resp, err := api.ReadinessWithResponse(ctx)
// If the API call is successful and the response is not nil,
// set the gRPC server to SERVING state and log a message.
if err == nil && resp.JSON200 != nil {
healthcheck.SetServingStatus("gripmock", healthgrpc.HealthCheckResponse_SERVING)
logger.Info().Msg("gRPC server is ready to accept requests")
return
}
}
}
}()
if err := s.Serve(lis); err != nil {
logger.Fatal().Err(err).Msg("failed to serve")
}
}
{{ template "find_stub" }}
{{ define "services" }}
type {{.Name}} struct{
{{.Package}}Unsafe{{.Name}}Server
__httpAddr__ string
}
{{ template "methods" .}}
{{ end }}
{{ define "methods" }}
{{ range .Methods}}
{{ if eq .MethodType "standard"}}
{{ template "standard_method" .}}
{{ else if eq .MethodType "server-stream"}}
{{ template "server_stream_method" .}}
{{ else if eq .MethodType "client-stream"}}
{{ template "client_stream_method" .}}
{{ else if eq .MethodType "bidirectional"}}
{{ template "bidirectional_method" .}}
{{ end }}
{{end}}
{{end}}
{{ define "standard_method" }}
func (s *{{.ServiceName}}) {{.TitleName}}(ctx context.Context, in *{{.Input}}) (*{{.Output}},error){
out := &{{.Output}}{}
// Retrieve metadata from the incoming context.
// The metadata is used to find the stub for the method being called.
md, _ := metadata.FromIncomingContext(ctx)
// Find the stub for the given service name, method name, and metadata.
// The stub defines the input and output messages for the method.
// If the stub is found, its output message is returned.
// If the stub is not found, an error is returned.
err := findStub(ctx, s.__httpAddr__, "{{.ServiceName}}", "{{.RpcName}}", md, in, out)
// Return the output message and any error encountered while finding the stub.
return out, err
}
{{ end }}
{{ define "server_stream_method" }}
func (s *{{.ServiceName}}) {{.TitleName}}(in *{{.Input}},srv {{.SvcPackage}}{{.ServiceName}}_{{.TitleName}}Server) error {
out := &{{.Output}}{}
// Retrieve metadata from the incoming context.
// The metadata is used to find the stub for the method being called.
ctx := srv.Context()
md, _ := metadata.FromIncomingContext(ctx)
// Find the stub for the given service name, method name, and metadata.
// The stub defines the input and output messages for the method.
// If the stub is found, its output message is returned.
// If the stub is not found, an error is returned.
err := findStub(ctx, s.__httpAddr__, "{{.ServiceName}}", "{{.RpcName}}", md, in, out)
if err != nil {
// Return the error encountered while finding the stub.
return err
}
// Send the output message back to the client.
// This will continue the server-streaming RPC.
// If there is an error sending the message, it will be returned.
return srv.Send(out)
}
{{ end }}
{{ define "client_stream_method"}}
func (s *{{.ServiceName}}) {{.TitleName}}(srv {{.SvcPackage}}{{.ServiceName}}_{{.TitleName}}Server) error {
out := &{{.Output}}{}
// Handle the client-streaming RPC.
// This loop will continue until the client closes the RPC.
// For each input message received from the client, it will find the stub
// and generate the output message.
// The output message will be sent back to the client when the RPC is closed.
ctx := srv.Context()
md, _ := metadata.FromIncomingContext(ctx)
for {
// Receive the next input message from the client.
// If the client closes the RPC, io.EOF is returned.
input, err := srv.Recv()
if errors.Is(err, io.EOF) {
// If the client closes the RPC, send the output message and close the RPC.
return srv.SendAndClose(out)
}
// Find the stub for the given service name, method name, and metadata.
// The stub defines the input and output messages for the method.
// If the stub is found, its output message is returned.
// If the stub is not found, an error is returned.
err = findStub(ctx, s.__httpAddr__, "{{.ServiceName}}","{{.RpcName}}", md, input, out)
if err != nil {
// If there is an error finding the stub, return the error.
return err
}
}
}
{{ end }}
{{ define "bidirectional_method"}}
func (s *{{.ServiceName}}) {{.TitleName}}(srv {{.SvcPackage}}{{.ServiceName}}_{{.TitleName}}Server) error {
// Handle the bidirectional RPC.
// This loop will continue until the client closes the RPC.
// For each input message received from the client, it will find the stub
// and generate the output message.
// The output message will be sent back to the client when the RPC is closed.
ctx := srv.Context()
md, _ := metadata.FromIncomingContext(ctx)
for {
// Receive the next input message from the client.
// If the client closes the RPC, io.EOF is returned.
input, err := srv.Recv()
if errors.Is(err, io.EOF) {
// If the client closes the RPC, send the output message and close the RPC.
return nil
}
if err != nil {
return err
}
// Create a new output message.
out := &{{.Output}}{}
// Find the stub for the given service name, method name, and metadata.
// The stub defines the input and output messages for the method.
// If the stub is found, its output message is returned.
// If the stub is not found, an error is returned.
err = findStub(ctx, s.__httpAddr__, "{{.ServiceName}}","{{.RpcName}}", md, input, out)
if err != nil {
return err
}
// Send the output message back to the client.
// If there is an error sending the message, it will be returned.
if err := srv.Send(out); err != nil{
return err
}
}
}
{{end}}
{{ define "register_services" }}
{{.Package}}Register{{.Name}}Server(s, &{{.Name}}{__httpAddr__: config.HTTPAddr})
{{ end }}
{{ define "find_stub" }}
func findStub(ctx context.Context, addr string, service, method string, md metadata.MD, in, out protoreflect.ProtoMessage) error {
// Create a new client with the configured HTTP address.
// Add the default HTTP client as the transport.
api, err := sdk.NewClientWithResponses(fmt.Sprintf("http://%s/api", addr),
sdk.WithHTTPClient(http.DefaultClient),
)
if err != nil {
return err
}
// Exclude headers that are not relevant for matching stubs.
excludes := []string{":authority", "content-type", "grpc-accept-encoding", "user-agent"}
// Create a map of headers to match with the input metadata.
headers := make(map[string]string, len(md))
for h, v := range md {
// Exclude headers that are not relevant for matching stubs.
if slices.Contains(excludes, h) {
continue
}
// Join the values of the header with a semicolon.
headers[h] = strings.Join(v, ";")
}
// Search for a stub that matches the given service, method, and headers.
searchStub, err := api.SearchStubsWithResponse(ctx, sdk.SearchStubsJSONRequestBody{
Service: service, // The name of the service.
Method: method, // The name of the method.
Headers: headers, // The headers to match.
Data: in, // The input message.
})
if err != nil {
return err
}
// If the search was unsuccessful, return an error with the response body.
if searchStub.JSON200 == nil {
return fmt.Errorf(string(searchStub.Body))
}
// If the search returned an error, return an error with the error code and message.
if searchStub.JSON200.Error != "" || searchStub.JSON200.Code != nil {
if searchStub.JSON200.Code == nil {
return status.Error(codes.Aborted, searchStub.JSON200.Error)
}
if *searchStub.JSON200.Code != codes.OK {
return status.Error(*searchStub.JSON200.Code, searchStub.JSON200.Error)
}
}
// Convert the search result to JSON.
data, err := json.Marshal(searchStub.JSON200.Data)
if err != nil {
return err
}
// Create a map of headers to set in the context.
mdResp := make(metadata.MD, len(searchStub.JSON200.Headers))
for k, v := range searchStub.JSON200.Headers {
// Split the values of the header by semicolon and trim each value.
splits := strings.Split(v, ";")
for i, s := range splits {
splits[i] = strings.TrimSpace(s)
}
mdResp[k] = splits
}
// Set the headers in the context.
grpc.SetHeader(ctx, mdResp)
// Unmarshal the search result into the output message.
return jsonpb.Unmarshal(data, out)
}
{{ end }}