Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 35 additions & 16 deletions pkg/telemetry/analytics/client.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package analytics

import (
"context"
"errors"
"sync"
"time"

Expand All @@ -25,21 +27,37 @@ func NewClient() Client {
return NewNoopClient()
}

phClient, err := posthog.NewWithConfig(posthogAPIKey, posthog.Config{
Endpoint: posthogEndpoint,
DisableGeoIP: new(false),
})
phClient, err := posthog.NewWithConfig(posthogAPIKey, posthogConfig(posthogEndpoint))
if err != nil {
log.Debugf("failed to initialize analytics client: %v", err)
return NewNoopClient()
}

return &client{phClient: phClient}
return &client{phClient: phClient, flushTimeout: flushTimeout}
}

func posthogConfig(endpoint string) posthog.Config {
return posthog.Config{
Endpoint: endpoint,
DisableGeoIP: new(false),
// Bounds Close as well, so no shutdown path can block the CLI.
ShutdownTimeout: flushTimeout,
Logger: quietLogger{},
}
}

// quietLogger keeps the SDK off stderr, which machine consumers parse.
type quietLogger struct{}

func (quietLogger) Debugf(format string, args ...any) { log.Debugf("posthog: "+format, args...) }
func (quietLogger) Logf(format string, args ...any) { log.Debugf("posthog: "+format, args...) }
func (quietLogger) Warnf(format string, args ...any) { log.Debugf("posthog: "+format, args...) }
func (quietLogger) Errorf(format string, args ...any) { log.Debugf("posthog: "+format, args...) }

type client struct {
phClient posthog.Client
closeOnce sync.Once
phClient posthog.Client
flushTimeout time.Duration
closeOnce sync.Once
}

func (c *client) RecordEvent(event Event) {
Expand Down Expand Up @@ -105,15 +123,16 @@ func (c *client) Flush() {
}
// The underlying client's Close drains the queue but can only be called once.
c.closeOnce.Do(func() {
done := make(chan error, 1)
go func() { done <- c.phClient.Close() }()
select {
case err := <-done:
if err != nil {
log.Debugf("error flushing analytics client: %v", err)
}
case <-time.After(flushTimeout):
log.Debugf("analytics flush timed out after %s; dropping queued events", flushTimeout)
// On deadline the SDK cancels the in-flight upload, so nothing keeps
// running after Flush returns.
ctx, cancel := context.WithTimeout(context.Background(), c.flushTimeout)
defer cancel()
switch err := c.phClient.CloseWithContext(ctx); {
case err == nil:
case errors.Is(err, context.DeadlineExceeded):
log.Debugf("analytics flush timed out after %s; dropping queued events", c.flushTimeout)
default:
log.Debugf("error flushing analytics client: %v", err)
}
})
}
107 changes: 102 additions & 5 deletions pkg/telemetry/analytics/client_test.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,31 @@
package analytics

import "testing"
import (
"io"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"

"github.com/posthog/posthog-go"
)

const (
eventGroup = "event"
userGroup = "user"
)

func TestBuildProperties_MergesEventAndUserWithoutCollision(t *testing.T) {
event := Event{
"event": {
eventGroup: {
KeyType: "devsy_workspace_count",
KeyMachineID: "m",
KeyTimestamp: int64(1),
"count": 7,
"version": "1.2.3",
},
"user": {
userGroup: {
KeyMachineID: "m",
KeyTimestamp: int64(1),
"os_name": "darwin",
Expand All @@ -36,13 +50,13 @@ func TestBuildProperties_MergesEventAndUserWithoutCollision(t *testing.T) {

func TestBuildProperties_ExcludesReservedKeys(t *testing.T) {
event := Event{
"event": {
eventGroup: {
KeyType: "devsy_cli",
KeyMachineID: "m",
KeyTimestamp: int64(1),
"command": "up",
},
"user": {
userGroup: {
KeyMachineID: "m",
KeyTimestamp: int64(1),
},
Expand All @@ -59,3 +73,86 @@ func TestBuildProperties_ExcludesReservedKeys(t *testing.T) {
t.Errorf("command = %v, want up", got["command"])
}
}

func newTestClient(t *testing.T, endpoint string, timeout time.Duration) *client {
t.Helper()
ph, err := posthog.NewWithConfig("test-key", posthogConfig(endpoint))
if err != nil {
t.Fatal(err)
}
return &client{phClient: ph, flushTimeout: timeout}
}

func testEvent() Event {
return Event{
eventGroup: {KeyType: "devsy_cli", KeyMachineID: "machine", "command": "up"},
userGroup: {KeyMachineID: "machine"},
}
}

func TestFlush_DeliversQueuedEvents(t *testing.T) {
var batches atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
batches.Add(1)
_, _ = w.Write([]byte(`{"status":1}`))
}))
t.Cleanup(srv.Close)

c := newTestClient(t, srv.URL, 5*time.Second)
c.RecordEvent(testEvent())
c.Flush()

if got := batches.Load(); got != 1 {
t.Fatalf("batches delivered = %d, want 1", got)
}
}

func TestFlush_CancelsHungUploadAtDeadline(t *testing.T) {
cancelled := make(chan struct{})
release := make(chan struct{})
srv := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
// The server only notices a closed connection after the body is read.
_, _ = io.Copy(io.Discard, r.Body)
select {
case <-r.Context().Done():
close(cancelled)
case <-release:
}
}))
// Cleanups run last in, first out: release the handler before Close waits on it.
t.Cleanup(srv.Close)
t.Cleanup(func() { close(release) })

const timeout = 200 * time.Millisecond
c := newTestClient(t, srv.URL, timeout)
c.RecordEvent(testEvent())

start := time.Now()
c.Flush()
if elapsed := time.Since(start); elapsed > 2*time.Second {
t.Fatalf("Flush took %s with a %s timeout", elapsed, timeout)
}

select {
case <-cancelled:
case <-time.After(2 * time.Second):
t.Fatal("in-flight upload was not cancelled after the deadline")
}
}

func TestFlush_SecondCallIsNoop(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`{"status":1}`))
}))
t.Cleanup(srv.Close)

c := newTestClient(t, srv.URL, time.Second)
c.RecordEvent(testEvent())
c.Flush()

start := time.Now()
c.Flush()
if elapsed := time.Since(start); elapsed > 100*time.Millisecond {
t.Fatalf("second Flush took %s", elapsed)
}
}
Loading