瀏覽代碼

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 年之前
父節點
當前提交
6f19bbfd5e
共有 1 個文件被更改,包括 16 次插入15 次删除
  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
+	}
 }