Răsfoiți Sursa

We can’t anymore “fire and forget”, now that metrics get posted right at the end, most of the time we’d loose them.
Give it max 50 ms to post metrics, that’s plenty, post call ends in ~2 ms or less when desktop is up, less than one ms to fail the post when DD is not listening.

Signed-off-by: Guillaume Tardif <[email protected]>

Guillaume Tardif 5 ani în urmă
părinte
comite
6f19bbfd5e
1 a modificat fișierele cu 16 adăugiri și 15 ștergeri
  1. 16 15
      metrics/client.go

+ 16 - 15
metrics/client.go

@@ -22,6 +22,7 @@ import (
 	"encoding/json"
 	"net"
 	"net/http"
+	"time"
 )
 
 type client struct {
@@ -71,23 +72,23 @@ func NewClient() Client {
 }
 
 func (c *client) Send(command Command) {
-	wasIn := make(chan bool)
-
-	// Fire and forget, we don't want to slow down the user waiting for DD
-	// metrics endpoint to respond. We could lose some events but that's ok.
+	result := make(chan bool, 1)
 	go func() {
-		defer func() {
-			_ = recover()
-		}()
-
-		wasIn <- true
+		postMetrics(command, c)
+		result <- true
+	}()
 
-		req, err := json.Marshal(command)
-		if err != nil {
-			return
-		}
+	// wait for the post finished, or timeout in case anything freezes.
+	// Posting metrics without Desktop listening returns in less than a ms, and a handful of ms (often <2ms) when Desktop is listening
+	select {
+	case <-result:
+	case <-time.After(50 * time.Millisecond):
+	}
+}
 
+func postMetrics(command Command, c *client) {
+	req, err := json.Marshal(command)
+	if err == nil {
 		_, _ = c.httpClient.Post("http://localhost/usage", "application/json", bytes.NewBuffer(req))
-	}()
-	<-wasIn
+	}
 }