Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: handle unit test bug on Playground API side #355

Merged
merged 10 commits into from
Jul 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/pull_request.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ jobs:
- name: Run ESLint
run: yarn lint
working-directory: ./web
- name: Run vitest
run: yarn test
working-directory: ./web
- name: Setup Go
uses: actions/setup-go@v5
with:
Expand Down
8 changes: 4 additions & 4 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
run:
tests: false
skip-dirs:
- pkg/worker
- cmd/webworker
- web
issues:
exclude-dirs:
- pkg/worker
- cmd/webworker
- web
exclude-rules:
- path: 'internal/gowasm/(.+)\.go'
linters:
Expand Down
26 changes: 14 additions & 12 deletions cmd/playground/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"context"
"errors"
"fmt"
"net/http"
"path/filepath"
Expand All @@ -14,8 +15,8 @@ import (
"github.com/x1unix/go-playground/internal/builder"
"github.com/x1unix/go-playground/internal/builder/storage"
"github.com/x1unix/go-playground/internal/config"
"github.com/x1unix/go-playground/internal/langserver"
"github.com/x1unix/go-playground/internal/langserver/webutil"
"github.com/x1unix/go-playground/internal/server"
"github.com/x1unix/go-playground/internal/server/webutil"
"github.com/x1unix/go-playground/pkg/goplay"
"github.com/x1unix/go-playground/pkg/util/cmdutil"
"github.com/x1unix/go-playground/pkg/util/osutil"
Expand Down Expand Up @@ -84,15 +85,15 @@ func start(goRoot string, logger *zap.Logger, cfg *config.Config) error {
// Initialize API endpoints
r := mux.NewRouter()
apiRouter := r.PathPrefix("/api").Subrouter()
svcCfg := langserver.ServiceConfig{Version: Version}
langserver.NewAPIv1Handler(svcCfg, playgroundClient, packages, buildSvc).
svcCfg := server.ServiceConfig{Version: Version}
server.NewAPIv1Handler(svcCfg, playgroundClient, packages, buildSvc).
Mount(apiRouter)

apiv2Router := apiRouter.PathPrefix("/v2").Subrouter()
langserver.NewAPIv2Handler(playgroundClient, buildSvc).Mount(apiv2Router)
server.NewAPIv2Handler(playgroundClient, buildSvc).Mount(apiv2Router)

// Web UI routes
tplVars := langserver.TemplateArguments{
tplVars := server.TemplateArguments{
GoogleTagID: cfg.Services.GoogleAnalyticsID,
}
if tplVars.GoogleTagID != "" {
Expand All @@ -104,24 +105,24 @@ func start(goRoot string, logger *zap.Logger, cfg *config.Config) error {
}

assetsDir := cfg.HTTP.AssetsDir
indexHandler := langserver.NewTemplateFileServer(zap.L(), filepath.Join(assetsDir, langserver.IndexFileName), tplVars)
spaHandler := langserver.NewSpaFileServer(assetsDir, tplVars)
indexHandler := server.NewTemplateFileServer(zap.L(), filepath.Join(assetsDir, server.IndexFileName), tplVars)
spaHandler := server.NewSpaFileServer(assetsDir, tplVars)
r.Path("/").
Handler(indexHandler)
r.Path("/snippet/{snippetID:[A-Za-z0-9_-]+}").
Handler(indexHandler)
r.PathPrefix("/").
Handler(spaHandler)

server := &http.Server{
srv := &http.Server{
Addr: cfg.HTTP.Addr,
Handler: r,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 15 * time.Second,
}

if err := startHttpServer(ctx, wg, server); err != nil {
if err := startHttpServer(ctx, wg, srv); err != nil {
return err
}

Expand All @@ -139,16 +140,17 @@ func startHttpServer(ctx context.Context, wg *sync.WaitGroup, server *http.Serve
defer wg.Done()
server.SetKeepAlivesEnabled(false)
if err := server.Shutdown(shutdownCtx); err != nil {
if err == context.Canceled {
if errors.Is(err, context.Canceled) {
return
}

logger.Errorf("Could not gracefully shutdown the server: %v\n", err)
}
}()

wg.Add(1)
logger.Infof("Listening on %q", server.Addr)
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
return fmt.Errorf("cannot start server on %q: %s", server.Addr, err)
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package langserver
package server

import (
"fmt"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package langserver
package server

import (
"context"
Expand Down Expand Up @@ -249,7 +249,7 @@ func (s *APIv1Handler) HandleRunCode(w http.ResponseWriter, r *http.Request) err
}
}

res, err := s.client.Compile(ctx, goplay.CompileRequest{
res, err := s.client.Evaluate(ctx, goplay.CompileRequest{
Version: goplay.DefaultVersion,
WithVet: params.Vet,
Body: src,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
package langserver
package server

import (
"context"
"encoding/json"
"errors"
"fmt"
"golang.org/x/time/rate"
Expand Down Expand Up @@ -140,15 +139,15 @@ func (h *APIv2Handler) HandleRun(w http.ResponseWriter, r *http.Request) error {
return NewBadRequestError(err)
}

payload, _, err := fileSetFromRequest(r)
snippet, err := evalPayloadFromRequest(r)
if err != nil {
return err
return NewBadRequestError(err)
}

res, err := h.client.Compile(ctx, goplay.CompileRequest{
res, err := h.client.Evaluate(ctx, goplay.CompileRequest{
Version: goplay.DefaultVersion,
WithVet: params.Vet,
Body: payload.Bytes(),
Body: snippet,
}, params.Backend)
if err != nil {
return err
Expand Down Expand Up @@ -202,56 +201,3 @@ func (h *APIv2Handler) Mount(r *mux.Router) {
r.Path("/share/{id}").Methods(http.MethodGet).HandlerFunc(WrapHandler(h.HandleGetSnippet))
r.Path("/compile").Methods(http.MethodPost).HandlerFunc(WrapHandler(h.HandleCompile))
}

func fileSetFromRequest(r *http.Request) (goplay.FileSet, []string, error) {
body, err := filesPayloadFromRequest(r)
if err != nil {
return goplay.FileSet{}, nil, err
}

payload := goplay.NewFileSet(goplay.MaxSnippetSize)
fileNames := make([]string, 0, len(body.Files))
for name, contents := range body.Files {
fileNames = append(fileNames, name)
if err := payload.Add(name, []byte(contents)); err != nil {
return payload, fileNames, NewBadRequestError(err)
}
}

return payload, fileNames, nil
}

func buildFilesFromRequest(r *http.Request) (map[string][]byte, error) {
body, err := filesPayloadFromRequest(r)
if err != nil {
return nil, err
}

files := make(map[string][]byte, len(body.Files))
for name, contents := range body.Files {
files[name] = []byte(contents)
}

return files, nil
}

func filesPayloadFromRequest(r *http.Request) (*FilesPayload, error) {
reader := http.MaxBytesReader(nil, r.Body, goplay.MaxSnippetSize)
defer reader.Close()

body := new(FilesPayload)
if err := json.NewDecoder(reader).Decode(body); err != nil {
maxBytesErr := new(http.MaxBytesError)
if errors.As(err, &maxBytesErr) {
return nil, ErrSnippetTooLarge
}

return nil, NewBadRequestError(err)
}

if len(body.Files) == 0 {
return nil, ErrEmptyRequest
}

return body, nil
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package langserver
package server

import (
"errors"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package langserver
package server

import (
"net/http"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package langserver
package server

import (
"bytes"
Expand Down
47 changes: 46 additions & 1 deletion internal/langserver/response.go → internal/server/response.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,61 @@
package langserver
package server

import (
"encoding/json"
"errors"
"fmt"
"net/http"
"path/filepath"
"strings"

"go.uber.org/zap"
)

const maxFilesCount = 10

type FilesPayload struct {
Files map[string]string `json:"files"`
}

// Validate checks file name and contents and returns error on validation failure.
func (p FilesPayload) Validate() error {
if len(p.Files) == 0 {
return errors.New("empty file list")
}

if len(p.Files) > maxFilesCount {
return fmt.Errorf("too many files (max: %d)", maxFilesCount)
}

for name, src := range p.Files {
switch filepath.Ext(name) {
case ".go", ".mod":
break
default:
return fmt.Errorf("invalid file type: %q", name)
}

if len(strings.TrimSpace(src)) == 0 {
return fmt.Errorf("empty file %q", name)
}
}

return nil
}

// HasUnitTests checks whether file list contains any unit test.
//
// Note: at the moment, func doesn't check file contents and only check file names.
func (p FilesPayload) HasUnitTests() bool {
for name := range p.Files {
if strings.HasSuffix(name, "_test.go") {
return true
}
}

return false
}

// ErrorResponse is error response
type ErrorResponse struct {
code int
Expand Down
Loading
Loading