Browse Source

mod debug

EUGENIO SOUZA CARVALHO 3 years ago
parent
commit
b70e6c4d76
6 changed files with 249 additions and 24 deletions
  1. 64 0
      api/debug.go
  2. 69 13
      api/mongo.go
  3. 26 3
      api/sse/hub.go
  4. 23 6
      api/utils.go
  5. 16 2
      translate/got/resources.go
  6. 51 0
      translate/tst/resources.go

+ 64 - 0
api/debug.go

@@ -0,0 +1,64 @@
+package api
+
+import (
+	"time"
+
+	"git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/api/errs"
+)
+
+type DebugStage struct {
+	DebugEvent `json:",inline"`
+	Events     []*DebugEvent `json:"events"`
+}
+
+type DebugEvent struct {
+	ID      string      `json:"id"`
+	Type    string      `json:"type"`
+	Status  string      `json:"status"`
+	Created int64       `json:"created"`
+	Error   *errs.Error `json:"error"`
+	Data    interface{} `json:"data"`
+}
+
+type DebugTaks struct {
+	ID           string        `json:"id"`
+	Status       string        `json:"status"`
+	Created      int64         `json:"created"`
+	Stages       []*DebugStage `json:"stages"`
+	CurrentStage *DebugStage   `json:"-"`
+}
+
+func NewDebugTaks() *DebugTaks {
+	return &DebugTaks{
+		Stages:       []*DebugStage{},
+		CurrentStage: &DebugStage{},
+	}
+}
+
+func (debug *DebugTaks) Stage(id string) *DebugStage {
+	stage := &DebugStage{}
+	stage.ID = id
+	debug.CurrentStage = stage
+	return stage
+}
+
+func (stage *DebugStage) PushEvent(event *DebugEvent) {
+	stage.Events = append(stage.Events, event)
+}
+
+func (debug *DebugTaks) Event(eventType, eventId string) *DebugEvent {
+
+	event := &DebugEvent{
+		ID:      eventId,
+		Type:    eventType,
+		Created: time.Now().Unix(),
+	}
+
+	debug.CurrentStage.PushEvent(event)
+
+	return event
+}
+
+func (debug *DebugTaks) Finalize() {
+	return
+}

+ 69 - 13
api/mongo.go

@@ -14,6 +14,7 @@ import (
 
 	"git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/api/errs"
 	"github.com/davecgh/go-spew/spew"
+	"github.com/kataras/iris"
 	iriscontext "github.com/kataras/iris/v12/context"
 	"go.mongodb.org/mongo-driver/bson"
 	"go.mongodb.org/mongo-driver/bson/primitive"
@@ -79,11 +80,11 @@ type Mongo struct {
 	// Password string `json:"password"`
 	// DataBase string `json:"database"`
 	// Addrs    string `json:"addrs"`
-	subject *BehaviorSubjectStruct
-	client  *mongo.Client
+	subject    *BehaviorSubjectStruct
+	client     *mongo.Client
 	Credential *options.Credential
-	Config  string `json:"config"`
-	Clients map[string]*mongo.Client
+	Config     string `json:"config"`
+	Clients    map[string]*mongo.Client
 }
 type execfn func(context.Context, *mongo.Collection)
 
@@ -97,10 +98,11 @@ type Filter struct {
 	UserId primitive.ObjectID
 	// NextPageToken primitive.ObjectID
 	// PageToken PageToken
-	Fields *bson.M
-	Query  *bson.M
-	Patchs *bson.A
-	Sort   *bson.M
+	Fields  *bson.M
+	Query   *bson.M
+	Patchs  *bson.A
+	Sort    *bson.M
+	Context *iriscontext.Context
 	// Sort       []string
 	Collection          string
 	QueryType           string
@@ -171,7 +173,7 @@ func (t *Mongo) Ready() *BehaviorSubjectStruct {
 }
 
 func (t *Mongo) Init() (err error) {
-	defer func(){
+	defer func() {
 		spew.Dump(err)
 	}()
 
@@ -245,7 +247,10 @@ func (t *Mongo) Dispatch(f *Filter) {
 }
 
 func (t *Mongo) InsertOne(f *Filter) (res *mongo.InsertOneResult, err *errs.Error) {
-
+	defer func() {
+		event := createDebugEvent(f, "models.insert.one")
+		event.Error = err
+	}()
 	f.Insertion = InsertOne
 
 	t.exec(f, func(ctx context.Context, collection *mongo.Collection) {
@@ -262,6 +267,10 @@ func (t *Mongo) InsertOne(f *Filter) (res *mongo.InsertOneResult, err *errs.Erro
 }
 
 func (t *Mongo) InsertMany(f *Filter) (res *mongo.InsertManyResult, err *errs.Error) {
+	defer func() {
+		event := createDebugEvent(f, "models.insert.many")
+		event.Error = err
+	}()
 
 	f.Insertion = InsertMany
 
@@ -285,6 +294,10 @@ func (t *Mongo) InsertMany(f *Filter) (res *mongo.InsertManyResult, err *errs.Er
 
 //Remove os elementos da colecao, selecionados pela query
 func (t *Mongo) RemoveOne(f *Filter) (res *mongo.DeleteResult, err *errs.Error) {
+	defer func() {
+		event := createDebugEvent(f, "models.remove.one")
+		event.Error = err
+	}()
 
 	f.CheckQuery = true
 
@@ -309,6 +322,11 @@ func (t *Mongo) RemoveOne(f *Filter) (res *mongo.DeleteResult, err *errs.Error)
 func (t *Mongo) RemoveMany(f *Filter) (res *mongo.DeleteResult, err *errs.Error) {
 	var lerr error
 
+	defer func() {
+		event := createDebugEvent(f, "models.remove.many")
+		event.Error = err
+	}()
+
 	f.CheckQuery = true
 
 	t.exec(f, func(ctx context.Context, collection *mongo.Collection) {
@@ -330,6 +348,11 @@ func (t *Mongo) RemoveMany(f *Filter) (res *mongo.DeleteResult, err *errs.Error)
 func (t *Mongo) UpdateOne(f *Filter) (res *mongo.UpdateResult, err *errs.Error) {
 	var lerr error
 
+	defer func() {
+		event := createDebugEvent(f, "models.update.one")
+		event.Error = err
+	}()
+
 	f.Insertion = InsertOne
 	f.CheckQuery = true
 
@@ -356,6 +379,11 @@ func (t *Mongo) UpdateMany(f *Filter) (res *mongo.UpdateResult, err *errs.Error)
 		value    = reflect.ValueOf(f.Entities)
 	)
 
+	defer func() {
+		event := createDebugEvent(f, "models.update.many")
+		event.Error = err
+	}()
+
 	f.Insertion = InsertMany
 	f.CheckQuery = true
 
@@ -431,9 +459,9 @@ func ParseQuery(ctx iriscontext.Context, filter *Filter, basequery string, data
 		})
 		return
 	}
-	
+
 	x := buf.Bytes()
-	
+
 	fmt.Println("buf.Bytes()", string(x))
 
 	if templateErr = bson.UnmarshalExtJSON(x, false, &filter.Query); templateErr != nil {
@@ -446,7 +474,10 @@ func ParseQuery(ctx iriscontext.Context, filter *Filter, basequery string, data
 }
 
 func (t *Mongo) PatchOne(f *Filter) (res *mongo.UpdateResult, err *errs.Error) {
-
+	defer func() {
+		event := createDebugEvent(f, "models.patch.one")
+		event.Error = err
+	}()
 	f.Insertion = Patch
 	f.CheckQuery = true
 
@@ -516,6 +547,10 @@ func (t *Mongo) PatchOne(f *Filter) (res *mongo.UpdateResult, err *errs.Error) {
 }
 
 func (t *Mongo) PatchMany(f *Filter) (res *mongo.UpdateResult, err *errs.Error) {
+	defer func() {
+		event := createDebugEvent(f, "models.patch.many")
+		event.Error = err
+	}()
 
 	f.Insertion = Patch
 	f.CheckQuery = true
@@ -603,6 +638,10 @@ func (mongo *Mongo) FindOneRx(options *Filter) *ObservableStruct {
 }
 
 func (t *Mongo) FindOne(f *Filter) (res *mongo.SingleResult, err *errs.Error) {
+	defer func() {
+		event := createDebugEvent(f, "models.find.one")
+		event.Error = err
+	}()
 
 	f.CheckQuery = (f.QueryType != "aggregate")
 
@@ -652,6 +691,10 @@ func findIds(filter *Filter) (ids []primitive.ObjectID) {
 func (t *Mongo) FindMany(f *Filter) (cursor *mongo.Cursor, err *errs.Error) {
 
 	// f.CheckQuery = true
+	defer func() {
+		event := createDebugEvent(f, "models.find.many")
+		event.Error = err
+	}()
 
 	t.exec(f, func(ctx context.Context, collection *mongo.Collection) {
 		var (
@@ -747,8 +790,21 @@ func (t *Mongo) FindMany(f *Filter) (cursor *mongo.Cursor, err *errs.Error) {
 	return
 }
 
+func createDebugEvent(options *Filter, eventType string) *DebugEvent {
+	debug := options.Context.Values().Get("#debug")
+	event := debug.Event(eventType)
+	event.Data = iris.Map{}
+	return event
+}
+
 func (models *Mongo) Exists(options *Filter) (exists bool, err *errs.Error) {
 
+	defer func() {
+		event := createDebugEvent(options, "models.exists")
+		event.Data = iris.Map{"response": exists}
+		event.Error = err
+	}()
+
 	options.Fields = &bson.M{"_id": 1}
 
 	if _, err = models.FindOne(options); err != nil {

+ 26 - 3
api/sse/hub.go

@@ -135,8 +135,9 @@ func (hub *SSEHub) Dispatch(event *Event, channels ...string) {
 		err    error
 		conn   = hub.RedisPool.Get()
 	)
-
 	defer conn.Close()
+	
+	eventBytes, _ := json.Marshal(event)
 
 	for _, channel := range channels {
 
@@ -144,13 +145,35 @@ func (hub *SSEHub) Dispatch(event *Event, channels ...string) {
 			continue
 		}
 
-		eventBytes, _ := json.Marshal(event)
-
 		conn.Do("RPUSH", channel, string(eventBytes))
 	}
+	
 	hub.consume <- true
 }
 
+func (hub *SSEHub) Close(channels ...string) {
+	var (
+		exists bool
+		count int
+		err    error
+		conn   = hub.RedisPool.Get()
+	)
+
+	for _, channel := range channels {
+		if exists, err = redis.Bool(conn.Do("HEXISTS", hub.ChannelCollection, channel)); err != nil || !exists {
+			continue
+		}
+		go func(channelID string) {
+			for {
+				if count, err = redis.Int(conn.Do("LLEN", channelID)); count > 0 {
+					continue
+				}
+				conn.Do("HDEL", hub.ChannelCollection, channelID)
+			}
+		}(channel)
+	}
+}
+
 func (hub *SSEHub) UpgradeConnection(ctx context.Context, channelId string) (err *errs.Error) {
 
 	var (

+ 23 - 6
api/utils.go

@@ -166,7 +166,7 @@ var (
 		AllowOrigin: []string{"*"},
 		// AllowOrigin:   []string{"http://localhost:4200"},
 		AllowMethods:  []string{"OPTIONS", "GET", "POST", "PUT", "DELETE", "PATCH"},
-		AllowHeaders:  []string{"Authorization", "Content-Type", "Origin", "Host", "x-api-build"},
+		AllowHeaders:  []string{"Accept", "Authorization", "Content-Type", "Origin", "Host", "x-api-build"},
 		ExposeHeaders: []string{"X-total-count"},
 	}
 
@@ -313,6 +313,11 @@ func finalizeRequest(ctx context.Context, resp interface{}, err *errs.Error) {
 
 	defer func() {
 		ctx.StopExecution()
+
+		if debug := ctx.Values().Get("#debug"); debug != nil {
+			debug.(*DebugTaks).Finalize()
+		}
+
 		if err != nil {
 
 			ctx.Application().Logger().Error(err.Error())
@@ -362,7 +367,7 @@ func finalizeRequest(ctx context.Context, resp interface{}, err *errs.Error) {
 		}
 	}
 	// default response case
-	ctx.WriteString("")
+	ctx.WriteString("invalid accept header value: " + accept)
 }
 
 // Call encapsula e trata os erros para cada requisição.
@@ -372,9 +377,21 @@ func CallAction(id string, fn func(context.Context) (interface{}, *errs.Error))
 			err      *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)
+		}
+
+		debug.Stage(id)
+
 		defer func() {
+
 			if !ctx.IsStopped() {
 
 				if _err := recover(); _err != nil {
@@ -437,8 +454,8 @@ func transactionHandler(ctx context.Context, action string) (err *errs.Error) {
 	case "commit":
 		operation = func() error { return contextSession.CommitTransaction(contextSession) }
 	}
-	
-	defer func ()  {
+
+	defer func() {
 		if localErr != nil {
 			err = errs.Internal().Details(&errs.Detail{
 				Message: localErr.Error(),
@@ -446,7 +463,7 @@ func transactionHandler(ctx context.Context, action string) (err *errs.Error) {
 		}
 	}()
 	try := 4
-	
+
 	for {
 		if localErr = operation(); localErr == nil {
 			fmt.Println(action, "executed ")
@@ -588,7 +605,7 @@ func DefaultCorsHandler() func(ctx context.Context) {
 
 func Cors(opt CorsOptions) func(ctx context.Context) {
 	return func(ctx context.Context) {
-		
+
 		ctx.Header("Access-Control-Allow-Credentials", "true")
 
 		if len(opt.AllowOrigin) > 0 {

+ 16 - 2
translate/got/resources.go

@@ -283,6 +283,10 @@ func GenIndexApi(p *Project) error {
 
 	// Inicializa o mapa de filtros da api
 	Index.Id(`
+		import(
+			"reflect"
+    		"runtime"
+		)
 		var (
 			filtersApiReference = map[string]*`).Qual(CODE_GEN_V2_COMMON, "ApiFilter").Id(`{}
 			FormatSelection = map[string]string{}
@@ -309,14 +313,24 @@ func GenIndexApi(p *Project) error {
 		}
 
 		func executeAction(ctx context.Context, actions ...func(context.Context) (interface{}, *`).Qual(API_ERROR, "Error").Id(`)) (resp interface{},err *errs.Error){
-			var stopPropagation bool
+			var (
+				stopPropagation bool
+				debug = ctx.Values().Get("#debug");
+				parts []string
+			)
 			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,
+				}
+
 				stopPropagation,_ = ctx.Values().GetBool("stop.propagation")
 				switch {
 				case stopPropagation, err != nil, resp != nil:
 					return
-					
 				}
 			}
 			return

+ 51 - 0
translate/tst/resources.go

@@ -271,6 +271,57 @@ func createAngularService(p *Project, module *TS.File) error {
 			// }
 		}
 
+		options(opts?: HttpOptions): HttpOptions {
+			console.log({ ...this.httpOptions.headers });
+			opts = Object.assign(
+			  {
+				headers: new HttpHeaders({
+				  ...this.httpOptions.headers,
+				}),
+				params: {},
+			  },
+			  opts
+			);
+		
+			// const headers = {
+			//   Authorization: this.Auth.Token(),
+			// };
+		
+			opts.headers.set("Authorization", this.Auth.Token());
+		
+			//this.copyHeader(this.httpOptions.headers, headers);
+			//this.copyHeader(opts.headers, headers);
+		
+			const params = opts.params;
+			// Converte a query para base64
+			if (params.q) {
+			  params.q = window.btoa(unescape(encodeURIComponent(params.q)));
+			}
+		
+			// delete opts.headers;
+			// delete opts.params;
+		
+			// const options = Object.assign(
+			//   {
+			//     headers: new HttpHeaders(headers),
+			//     params: new HttpParams({ fromObject: params }),
+			//   },
+			//   opts
+			// );
+		
+			// const options = Object.assign({
+			// 	headers: new HttpHeaders(hopts),
+			// 	params: {}
+			// }, opts);
+		
+			// // Converte a query para base64
+			// if (options.params.q) {
+			// 	options.params.q = window.btoa(unescape(encodeURIComponent(options.params.q)));
+			// }
+		
+			return opts;
+		  }
+		  
 		options(opts?: HttpOptions): HttpOptions {
 
 			opts = Object.assign({