Skip to content

Commit

Permalink
bugfix
Browse files Browse the repository at this point in the history
  • Loading branch information
rez1dent3 committed Jul 7, 2024
1 parent 9340cfc commit 40b2a7c
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 52 deletions.
29 changes: 14 additions & 15 deletions internal/app/rest_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
"log"
"net/http"
"os"
"path/filepath"
"path"
"strings"
"sync/atomic"
"time"
Expand Down Expand Up @@ -50,6 +50,7 @@ func NewRestServer(path string, reflector *grpcreflector.GReflector) (*RestServe

if path != "" {
server.readStubs(path) // TODO: someday you will need to rewrite this code
server.ok.Store(true)
}

return server, nil
Expand Down Expand Up @@ -289,33 +290,30 @@ func (h *RestServer) writeResponseError(err error, w http.ResponseWriter) {
// and adds them to the server's stub store.
// The stub files can be in yaml or json format.
// If a file is in yaml format, it will be converted to json format.
func (h *RestServer) readStubs(path string) {
defer h.ok.Store(true)

files, err := os.ReadDir(path)
func (h *RestServer) readStubs(pathDir string) {
files, err := os.ReadDir(pathDir)
if err != nil {
log.Printf("can't read stubs from %s: %v", path, err)
log.Printf("can't read stubs from %s: %v", pathDir, err)

return
}

for _, file := range files {
// If the file is a directory, recursively read its stubs.
if file.IsDir() {
h.readStubs(filepath.Join(path, file.Name()))
continue
}
h.readStubs(path.Join(pathDir, file.Name()))

// Only process files with yaml or yml extensions.
if !strings.HasSuffix(file.Name(), ".yaml") && !strings.HasSuffix(file.Name(), ".yml") {
continue
}

// Read the stub file and add it to the server's stub store.
stubs, err := h.readStub(filepath.Join(path, file.Name()))
stubs, err := h.readStub(path.Join(pathDir, file.Name()))
if err != nil {
log.Printf("cant read stubs from %s: %v", file.Name(), err)

continue
}

h.stuber.PutMany(stubs...)
}
}
Expand All @@ -327,21 +325,21 @@ func (h *RestServer) readStub(path string) ([]*stuber.Stub, error) {
// Read the file
byt, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("error when reading file %s: %v", path, err)
return nil, fmt.Errorf("error when reading file %s: %w", path, err)
}

// If the file is in yaml format, convert it to json format
if strings.HasSuffix(path, ".yaml") || strings.HasSuffix(path, ".yml") {
byt, err = h.convertor.Execute(path, byt)
if err != nil {
return nil, fmt.Errorf("error when unmarshalling file %s: %v", path, err)
return nil, fmt.Errorf("error when unmarshalling file %s: %w", path, err)
}
}

// Unmarshal the json into a slice of stubs
var stubs []*stuber.Stub
if err := jsondecoder.UnmarshalSlice(byt, &stubs); err != nil {
return nil, fmt.Errorf("error when unmarshalling file %s: %v %s", path, string(byt), err)
return nil, fmt.Errorf("error when unmarshalling file %s: %v %w", path, string(byt), err)
}

return stubs, nil
Expand Down Expand Up @@ -371,6 +369,7 @@ func validateStub(stub *stuber.Stub) error {
}

if stub.Output.Error == "" && stub.Output.Data == nil && stub.Output.Code == nil {
//nolint:goerr113,perfsprint
return fmt.Errorf("output cannot be empty")
}

Expand Down
27 changes: 0 additions & 27 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,12 @@ import (
"path/filepath"
"strings"
"syscall"
"time"

_ "github.com/gripmock/grpc-interceptors"
"github.com/rs/zerolog"
_ "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
_ "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"google.golang.org/grpc"
_ "google.golang.org/grpc/health"
healthv1 "google.golang.org/grpc/health/grpc_health_v1"

_ "github.com/bavix/gripmock-sdk-go"
"github.com/bavix/gripmock/internal/pkg/patcher"
Expand Down Expand Up @@ -115,30 +112,6 @@ func main() {
// And run
run, chErr := runGrpcServer(ctx, output)

// Wait for the gRPC server to start and confirm that it is in the "SERVING" state.
// This is done by checking the health check service on the server.
// If the service is in the "SERVING" state, it means that the server has started successfully.
go func() {
ctx, cancel := context.WithTimeout(ctx, time.Minute)
defer cancel()

waiter := healthv1.NewHealthClient(builder.GRPCClient())

// Check the health of the server.
// The empty string in the request means that we want to check the whole server,
// not a specific service.
// The grpc.WaitForReady(true) parameter means that we want to wait for the server to become ready.
check, err := waiter.Check(ctx, &healthv1.HealthCheckRequest{Service: ""}, grpc.WaitForReady(true))
if err != nil {
return
}

// If the server is in the "SERVING" state, send a signal to the chReady channel.
if check.GetStatus() == healthv1.HealthCheckResponse_SERVING {
zerolog.Ctx(ctx).Info().Msg("gRPC server is ready to accept requests")
}
}()

// Wait for the gRPC server to exit or the context to be done.
select {
case err := <-chErr:
Expand Down
2 changes: 2 additions & 0 deletions protoc-gen-gripmock/server.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ func main() {
if err == nil && resp.JSON200 != nil {
healthcheck.SetServingStatus("", healthgrpc.HealthCheckResponse_SERVING)

builder.Logger().Info().Msg("gRPC server is ready to accept requests")

return
}
}
Expand Down
16 changes: 6 additions & 10 deletions stub/stub.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,6 @@ func RunRestServer(
config environment.Config,
reflector *grpcreflector.GReflector,
) {
const timeout = time.Millisecond * 25

apiServer, _ := app.NewRestServer(stubPath, reflector)

ui, _ := gripmockui.Assets()
Expand All @@ -41,6 +39,8 @@ func RunRestServer(
})
router.PathPrefix("/").Handler(http.FileServerFS(ui)).Methods(http.MethodGet)

const timeout = time.Millisecond * 25

srv := &http.Server{
Addr: config.HTTPAddr,
ReadHeaderTimeout: timeout,
Expand All @@ -62,12 +62,8 @@ func RunRestServer(
Str("addr", config.HTTPAddr).
Msg("stub-manager started")

go func() {
// nosemgrep:go.lang.security.audit.net.use-tls.use-tls
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
zerolog.Ctx(ctx).Fatal().Err(err).Msg("stub manager completed")
}
}()

<-ctx.Done()
// nosemgrep:go.lang.security.audit.net.use-tls.use-tls
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
zerolog.Ctx(ctx).Fatal().Err(err).Msg("stub manager completed")
}
}

0 comments on commit 40b2a7c

Please sign in to comment.