EUGENIO SOUZA CARVALHO 3 years ago
parent
commit
c0cb0bee63
4 changed files with 107 additions and 17 deletions
  1. 76 2
      api/debug.go
  2. 2 8
      api/utils.go
  3. 1 0
      go.sum
  4. 28 7
      translate/got/resources.go

+ 76 - 2
api/debug.go

@@ -1,9 +1,15 @@
 package api
 
 import (
+	"encoding/json"
+	"os"
 	"time"
 
 	"git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/api/errs"
+	"git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/api/sse"
+	"github.com/kataras/iris"
+	context "github.com/kataras/iris/v12/context"
+	"go.mongodb.org/mongo-driver/bson/primitive"
 )
 
 type DebugStage struct {
@@ -26,6 +32,7 @@ type DebugTaks struct {
 	Created      int64         `json:"created"`
 	Stages       []*DebugStage `json:"stages"`
 	CurrentStage *DebugStage   `json:"-"`
+	Debug        *Debugger     `json:"-"`
 }
 
 func NewDebugTaks() *DebugTaks {
@@ -59,6 +66,73 @@ func (debug *DebugTaks) Event(eventType, eventId string) *DebugEvent {
 	return event
 }
 
-func (debug *DebugTaks) Finalize() {
-	return
+func (task *DebugTaks) Finalize() {
+	var (
+		debug   = task.Debug
+		out     []byte
+		err     error
+		channel = debug.Hub.GetChannel(debug.ChannelID)
+	)
+
+	if out, err = json.Marshal(task); err != nil {
+		channel.Emit(&sse.Event{
+			Kind:    "debugger.error",
+			Payload: err.Error(),
+		})
+	} else {
+		channel.Emit(&sse.Event{
+			Kind:    "request",
+			Payload: string(out),
+		})
+	}
+}
+
+type Debugger struct {
+	ChannelID string
+	Tasks     []*DebugTaks
+	Hub       *sse.SSEHub
+}
+
+func (debug *Debugger) Handler() func(context.Context) {
+	return func(ctx context.Context) {
+		ctx.Values().Set("#debug", debug.CreateTask())
+	}
+}
+
+func (debug *Debugger) CreateTask() *DebugTaks {
+	task := &DebugTaks{
+		ID:      primitive.NewObjectID().Hex(),
+		Status:  "",
+		Created: time.Now().Unix(),
+		Debug:   debug,
+	}
+	debug.Tasks = append(debug.Tasks, task)
+	return task
+}
+
+func (debug *Debugger) EventStream() func(context.Context) {
+	return func(ctx context.Context) {
+		if err := debug.Hub.UpgradeConnection(
+			ctx,
+			debug.ChannelID,
+		); err != nil {
+			ctx.JSON(iris.Map{
+				"err": err,
+			})
+			return
+		}
+		ctx.JSON(iris.Map{})
+	}
+}
+
+func NewDebug() *Debugger {
+	return &Debugger{
+		ChannelID: "debug",
+		Tasks:     []*DebugTaks{},
+		Hub: sse.NewSSEHub(&sse.SSEOptions{
+			URI:               os.Getenv("REDIS_URI"),
+			Password:          os.Getenv("REDIS_PASSWD"),
+			ChannelCollection: "debugger",
+		}),
+	}
 }

+ 2 - 8
api/utils.go

@@ -378,18 +378,12 @@ func CallAction(id string, fn func(context.Context) (interface{}, *errs.Error))
 			resp     interface{}
 			finalize = true
 			values   = ctx.Values()
-			debug    *DebugTaks
 		)
 
-		if interfaceDebug := values.Get("#debug"); interfaceDebug != nil {
-			debug = interfaceDebug.(*DebugTaks)
-		} else {
-			debug = NewDebugTaks()
-			values.Set("#debug", debug)
+		if debug, activeDebug := values.Get("#debug").(*DebugTaks); activeDebug {
+			debug.Stage(id)
 		}
 
-		debug.Stage(id)
-
 		defer func() {
 
 			if !ctx.IsStopped() {

+ 1 - 0
go.sum

@@ -242,6 +242,7 @@ golang.org/x/tools v0.0.0-20190327201419-c70d86f8b7cf/go.mod h1:LCzVGOaR6xXOjkQ3
 golang.org/x/tools v0.0.0-20190329151228-23e29df326fe/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
 golang.org/x/tools v0.0.0-20190416151739-9c9e1878f421/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
 golang.org/x/tools v0.0.0-20190420181800-aa740d480789/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
+golang.org/x/tools v0.0.0-20190531172133-b3315ee88b7d h1:bt+R27hbE7uVf7PY9S6wpNg9Xo2WRe/XQT0uGq9RQQw=
 golang.org/x/tools v0.0.0-20190531172133-b3315ee88b7d/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
 gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
 gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=

+ 28 - 7
translate/got/resources.go

@@ -285,11 +285,13 @@ func GenIndexApi(p *Project) error {
 	Index.Id(`
 		import(
 			"reflect"
-    		"runtime"
+			"runtime"
+			"strings"
 		)
 		var (
 			filtersApiReference = map[string]*`).Qual(CODE_GEN_V2_COMMON, "ApiFilter").Id(`{}
 			FormatSelection = map[string]string{}
+			Debug = api.NewDebug()
 		)
 		func init(){
 			var (
@@ -310,21 +312,24 @@ func GenIndexApi(p *Project) error {
 					filtersApiReference[entity.Id] = entity
 				}
 			}
+
 		}
 
 		func executeAction(ctx context.Context, actions ...func(context.Context) (interface{}, *`).Qual(API_ERROR, "Error").Id(`)) (resp interface{},err *errs.Error){
 			var (
 				stopPropagation bool
-				debug = ctx.Values().Get("#debug");
 				parts []string
 			)
+			debug, debugActive := ctx.Values().Get("#debug").(*api.DebugTaks);
+			
 			for _, action := range actions {
-				parts = strings.Split(runtime.FuncForPC(reflect.ValueOf(action).Pointer()).Name(), ".")
-				event := debug.Event("execute.action", parts[len(parts)-1])
 				resp, err = action(ctx)
-				event.Data = iris.M{
-					"resp": resp, 
-					"err": err,
+				
+				if debugActive {
+					parts = strings.Split(runtime.FuncForPC(reflect.ValueOf(action).Pointer()).Name(), ".")
+					event := debug.Event("execute.action", parts[len(parts)-1])
+					event.Data = resp
+					event.Error = err
 				}
 
 				stopPropagation,_ = ctx.Values().GetBool("stop.propagation")
@@ -346,6 +351,7 @@ func GenIndexApi(p *Project) error {
 			args := []G.Code{
 				G.Lit(method.HttpMethod),
 				G.Lit(p.GetPath(method)),
+				G.Lit("Debug.Handler()"),
 			}
 
 			middlewares = []string{}
@@ -418,6 +424,21 @@ func GenIndexApi(p *Project) error {
 	// 	G.Id(fmt.Sprintf(`FilterHandle("../api/%s/filters")`, p.Package)),
 	// ))
 
+	statments = append(statments, G.Line().Comment("Debug eventstream").Line().Id("app").Dot("Get").Call(
+		G.Lit("/debug"),
+		G.Id(`apply("debug", Debug.EventStream())`),
+		// G.Func().Params(G.Id("ctx").Qual(IRIS_CTX, "Context")).Block(
+
+		// 	G.Id(`
+		// 		if err = asyncTaskManagerService.Hub.UpgradeConnection(
+		// 		 	ctx,
+		// 		 	fmt.Sprintf("async.task.%s", asyncTaskId),
+		// 		); err != nil {
+		// 			ctx.
+		// 		}
+		// 	`),
+		// ),
+	))
 	// Cria a funcao que trata os metodos options
 	statments = append(statments, G.Line().Comment("Options request").Line().Id("app").Dot("Options").Call(
 		G.Lit("/{url:path}"),