github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/modules/metrics/auto_collect.go (about)

     1  package metrics
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  
     7  	"github.com/tidwall/gjson"
     8  
     9  	"github.com/machinefi/w3bstream/pkg/depends/kit/logr"
    10  	"github.com/machinefi/w3bstream/pkg/models"
    11  )
    12  
    13  var autoCollectCli = NewSQLBatcher("INSERT INTO ws_metrics.auto_collect_metrics VALUES")
    14  
    15  var (
    16  	lonkeys = []string{"lon", "Lon", "long", "Long", "longitude", "Longitude"}
    17  	latkeys = []string{"lat", "latitude", "Lat", "Latitude"}
    18  )
    19  
    20  func GeoCollect(ctx context.Context, v *models.Event) {
    21  	ctx, l := logr.Start(ctx, "metrics.GeoCollect")
    22  	defer l.End()
    23  
    24  	var (
    25  		lon    float64
    26  		lat    float64
    27  		haslon = false
    28  		haslat = false
    29  		data   = string(v.Input)
    30  	)
    31  
    32  	for _, key := range lonkeys {
    33  		if r := gjson.Get(data, key); r.Exists() {
    34  			lon = r.Float()
    35  			haslon = true
    36  			break
    37  		}
    38  	}
    39  	if !haslon {
    40  		return
    41  	}
    42  
    43  	for _, key := range latkeys {
    44  		if r := gjson.Get(data, key); r.Exists() {
    45  			lat = r.Float()
    46  			haslat = true
    47  			break
    48  		}
    49  	}
    50  	if !haslat {
    51  		return
    52  	}
    53  
    54  	geodata := fmt.Sprintf(`{"longitude": %f, "latitude": %f}`, lon, lat)
    55  	if err := autoCollectCli.Insert(fmt.Sprintf(`now(), '%s', '%s', '%s', '%s'`, v.AccountID.String(), v.ProjectName, v.PublisherKey, geodata)); err != nil {
    56  		l.WithValues("eid", v.EventID).Error(err)
    57  	}
    58  }