github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/cmd/usage/usage.go (about)

     1  // Package usage tracks micro usage
     2  package usage
     3  
     4  import (
     5  	"bytes"
     6  	"crypto/sha256"
     7  	"fmt"
     8  	"io"
     9  	"io/ioutil"
    10  	"net/http"
    11  	"os"
    12  	"time"
    13  
    14  	"github.com/golang/protobuf/proto"
    15  	"github.com/google/uuid"
    16  	pb "github.com/tickoalcantara12/micro/v3/cmd/usage/proto"
    17  )
    18  
    19  var (
    20  	// usage url
    21  	u = "https://micro.dev/usage"
    22  	// usage agent
    23  	a = "micro/usage"
    24  	// usage version
    25  	v = "1549376196832741000"
    26  	// 24 hour window
    27  	w = 8.64e13
    28  )
    29  
    30  // New generates a new usage report to be filled in
    31  func New(service string) *pb.Usage {
    32  	id := fmt.Sprintf("micro.%s.%s.%s", service, v, uuid.New().String())
    33  	srv := "micro." + service
    34  
    35  	if len(service) == 0 {
    36  		id = fmt.Sprintf("micro.%s.%s", v, uuid.New().String())
    37  		srv = "micro"
    38  	}
    39  
    40  	sum := sha256.Sum256([]byte(id))
    41  
    42  	return &pb.Usage{
    43  		Service:   srv,
    44  		Version:   v,
    45  		Id:        fmt.Sprintf("%x", sum),
    46  		Timestamp: uint64(time.Now().UnixNano()),
    47  		Window:    uint64(w),
    48  		Metrics: &pb.Metrics{
    49  			Count: make(map[string]uint64),
    50  		},
    51  	}
    52  }
    53  
    54  // Report reports the current usage
    55  func Report(ug *pb.Usage) error {
    56  	if v := os.Getenv("MICRO_REPORT_USAGE"); v == "false" {
    57  		return nil
    58  	}
    59  
    60  	// update timestamp/window
    61  	now := uint64(time.Now().UnixNano())
    62  	ug.Window = now - ug.Timestamp
    63  	ug.Timestamp = now
    64  
    65  	p, err := proto.Marshal(ug)
    66  	if err != nil {
    67  		return err
    68  	}
    69  	req, err := http.NewRequest("POST", u, bytes.NewReader(p))
    70  	if err != nil {
    71  		return err
    72  	}
    73  	req.Header.Set("Content-Type", "application/protobuf")
    74  	req.Header.Set("User-Agent", a)
    75  	rsp, err := http.DefaultClient.Do(req)
    76  	if err != nil {
    77  		return err
    78  	}
    79  	defer rsp.Body.Close()
    80  	io.Copy(ioutil.Discard, rsp.Body)
    81  	return nil
    82  }