From 98c34fb45bffaa8e051cdd88cac1fb9c22cbe18a Mon Sep 17 00:00:00 2001 From: Ani Date: Tue, 4 Aug 2026 15:36:57 +0530 Subject: [PATCH] feat(waitlist): notify dash via cairo on access applications Fire-and-forget POST /v2/track after a successful waitlist submit so Dash can relay applications without blocking signup UX. Co-authored-by: Cursor --- cmd/coordinator/main.go | 11 +++ deploy/env.example | 6 ++ internal/coordinator/cairo/tracker.go | 109 +++++++++++++++++++++ internal/coordinator/cairo/tracker_test.go | 98 ++++++++++++++++++ internal/coordinator/config/config.go | 9 ++ internal/coordinator/httpapi/health.go | 2 + internal/coordinator/httpapi/waitlist.go | 13 ++- 7 files changed, 247 insertions(+), 1 deletion(-) create mode 100644 internal/coordinator/cairo/tracker.go create mode 100644 internal/coordinator/cairo/tracker_test.go diff --git a/cmd/coordinator/main.go b/cmd/coordinator/main.go index 54f1f25..aea6fc1 100644 --- a/cmd/coordinator/main.go +++ b/cmd/coordinator/main.go @@ -11,6 +11,7 @@ import ( "time" "github.com/Ani-HQ/thirdshift/internal/coordinator/auth" + "github.com/Ani-HQ/thirdshift/internal/coordinator/cairo" "github.com/Ani-HQ/thirdshift/internal/coordinator/config" "github.com/Ani-HQ/thirdshift/internal/coordinator/httpapi" "github.com/Ani-HQ/thirdshift/internal/coordinator/jobs" @@ -75,6 +76,12 @@ func run() error { if err != nil { return err } + cairoTracker := &cairo.Tracker{ + Host: cfg.CairoHost, + WriteKey: cfg.CairoWriteKey, + Namespace: cfg.CairoNamespace, + Logger: logger, + } handler = httpapi.NewMuxWithOptions(httpapi.Options{ Version: cfg.Version, Registration: registration.Service{ @@ -89,8 +96,12 @@ func run() error { OperatorToken: cfg.OperatorToken, HeartbeatInterval: cfg.HeartbeatInterval, RequesterRegionHeader: cfg.RequesterRegionHeader, + Cairo: cairoTracker, Logger: logger, }) + if cairoTracker.Enabled() { + logger.Info("cairo waitlist notifications enabled", "host", cfg.CairoHost, "namespace", cfg.CairoNamespace) + } } server := &http.Server{ diff --git a/deploy/env.example b/deploy/env.example index 38cfdb3..94b1b21 100644 --- a/deploy/env.example +++ b/deploy/env.example @@ -22,3 +22,9 @@ THIRDSHIFT_SCHEDULER_WEIGHT_FAIRNESS=5 THIRDSHIFT_SCHEDULER_WEIGHT_REGION=5 NEXT_PUBLIC_BASE_PATH= NEXT_PUBLIC_THIRDSHIFT_API_BASE= + +# Optional: notify Dash via Cairo on waitlist submit (POST /v2/track). +# Create with Cairo setup_product / create_write_key; leave unset to disable. +CAIRO_HOST= +CAIRO_WRITE_KEY= +CAIRO_NAMESPACE=default diff --git a/internal/coordinator/cairo/tracker.go b/internal/coordinator/cairo/tracker.go new file mode 100644 index 0000000..2b4becd --- /dev/null +++ b/internal/coordinator/cairo/tracker.go @@ -0,0 +1,109 @@ +package cairo + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "log/slog" + "net/http" + "strings" + "time" +) + +const accessApplicationEvent = "access_application" + +// Tracker posts product events to Cairo's /v2/track ingest. +// Missing Host or WriteKey disables tracking (no-op). +type Tracker struct { + Host string + WriteKey string + Namespace string + Client *http.Client + Logger *slog.Logger +} + +type trackRequest struct { + Type string `json:"type"` + Event string `json:"event"` + UserID string `json:"userId,omitempty"` + Namespace string `json:"namespace,omitempty"` + Properties map[string]any `json:"properties,omitempty"` + Timestamp string `json:"timestamp,omitempty"` +} + +// Enabled reports whether the tracker can reach Cairo. +func (t *Tracker) Enabled() bool { + return t != nil && strings.TrimSpace(t.Host) != "" && strings.TrimSpace(t.WriteKey) != "" +} + +// TrackAccessApplication notifies Dash (via Cairo rules) about a waitlist submit. +// Failures are logged only; callers should treat this as fire-and-forget. +func (t *Tracker) TrackAccessApplication(ctx context.Context, email string, properties map[string]any) error { + return t.Track(ctx, accessApplicationEvent, email, properties) +} + +// Track posts a single event. Returns nil when the tracker is disabled. +func (t *Tracker) Track(ctx context.Context, event, userID string, properties map[string]any) error { + if !t.Enabled() { + return nil + } + event = strings.TrimSpace(event) + if event == "" { + return fmt.Errorf("cairo track: event is required") + } + body := trackRequest{ + Type: "track", + Event: event, + UserID: strings.TrimSpace(userID), + Namespace: strings.TrimSpace(t.Namespace), + Properties: properties, + Timestamp: time.Now().UTC().Format(time.RFC3339), + } + payload, err := json.Marshal(body) + if err != nil { + return fmt.Errorf("cairo track: encode: %w", err) + } + url := strings.TrimRight(t.Host, "/") + "/v2/track" + req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(payload)) + if err != nil { + return fmt.Errorf("cairo track: request: %w", err) + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Write-Key", t.WriteKey) + + client := t.Client + if client == nil { + client = &http.Client{Timeout: 5 * time.Second} + } + res, err := client.Do(req) + if err != nil { + return fmt.Errorf("cairo track: %w", err) + } + defer res.Body.Close() + _, _ = io.Copy(io.Discard, io.LimitReader(res.Body, 64<<10)) + if res.StatusCode < 200 || res.StatusCode >= 300 { + return fmt.Errorf("cairo track: unexpected status %d", res.StatusCode) + } + return nil +} + +// NotifyAccessApplicationAsync tracks in a background goroutine and never +// blocks the waitlist response path. +func (t *Tracker) NotifyAccessApplicationAsync(email string, properties map[string]any) { + if !t.Enabled() { + return + } + go func() { + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + if err := t.TrackAccessApplication(ctx, email, properties); err != nil { + logger := t.Logger + if logger == nil { + logger = slog.Default() + } + logger.Warn("cairo access_application track failed", "error", err) + } + }() +} diff --git a/internal/coordinator/cairo/tracker_test.go b/internal/coordinator/cairo/tracker_test.go new file mode 100644 index 0000000..3b9b524 --- /dev/null +++ b/internal/coordinator/cairo/tracker_test.go @@ -0,0 +1,98 @@ +package cairo + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" +) + +func TestTrackerDisabled(t *testing.T) { + var tracker *Tracker + if tracker.Enabled() { + t.Fatal("nil tracker should be disabled") + } + if err := (&Tracker{}).Track(context.Background(), "access_application", "a@b.com", nil); err != nil { + t.Fatalf("disabled tracker should no-op: %v", err) + } +} + +func TestTrackAccessApplication(t *testing.T) { + var gotPath atomic.Value + var gotKey atomic.Value + var gotBody atomic.Value + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotPath.Store(r.URL.Path) + gotKey.Store(r.Header.Get("X-Write-Key")) + body, _ := io.ReadAll(r.Body) + gotBody.Store(body) + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"success":true}`)) + })) + defer server.Close() + + tracker := &Tracker{ + Host: server.URL, + WriteKey: "ck_test", + Namespace: "default", + Client: server.Client(), + } + if err := tracker.TrackAccessApplication(context.Background(), "dev@example.com", map[string]any{ + "use_case": "Prototype", + "is_new": true, + }); err != nil { + t.Fatalf("track: %v", err) + } + if gotPath.Load() != "/v2/track" { + t.Fatalf("path = %v", gotPath.Load()) + } + if gotKey.Load() != "ck_test" { + t.Fatalf("write key = %v", gotKey.Load()) + } + var payload map[string]any + if err := json.Unmarshal(gotBody.Load().([]byte), &payload); err != nil { + t.Fatalf("decode body: %v", err) + } + if payload["type"] != "track" || payload["event"] != "access_application" { + t.Fatalf("payload = %#v", payload) + } + if payload["userId"] != "dev@example.com" || payload["namespace"] != "default" { + t.Fatalf("identity fields = %#v", payload) + } + props, _ := payload["properties"].(map[string]any) + if props["use_case"] != "Prototype" || props["is_new"] != true { + t.Fatalf("properties = %#v", props) + } +} + +func TestTrackUnexpectedStatus(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusUnauthorized) + })) + defer server.Close() + tracker := &Tracker{Host: server.URL, WriteKey: "ck_test", Client: server.Client()} + if err := tracker.Track(context.Background(), "access_application", "a@b.com", nil); err == nil { + t.Fatal("expected error for non-2xx") + } +} + +func TestNotifyAccessApplicationAsync(t *testing.T) { + done := make(chan struct{}) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"success":true}`)) + close(done) + })) + defer server.Close() + tracker := &Tracker{Host: server.URL, WriteKey: "ck_test", Client: server.Client()} + tracker.NotifyAccessApplicationAsync("dev@example.com", map[string]any{"is_new": true}) + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatal("async track did not run") + } +} diff --git a/internal/coordinator/config/config.go b/internal/coordinator/config/config.go index 92cfb99..fdb6964 100644 --- a/internal/coordinator/config/config.go +++ b/internal/coordinator/config/config.go @@ -34,6 +34,9 @@ const ( envAlertRuntimeCrash = "THIRDSHIFT_ALERT_RUNTIME_CRASH_THRESHOLD" envAlertAuthAnomaly = "THIRDSHIFT_ALERT_AUTH_ANOMALY_THRESHOLD" envRequesterRegionHeader = "THIRDSHIFT_REQUESTER_REGION_HEADER" + envCairoHost = "CAIRO_HOST" + envCairoWriteKey = "CAIRO_WRITE_KEY" + envCairoNamespace = "CAIRO_NAMESPACE" ) type Config struct { @@ -50,6 +53,9 @@ type Config struct { CreditHold time.Duration Alerts operatorstore.AlertConfig RequesterRegionHeader string + CairoHost string + CairoWriteKey string + CairoNamespace string } func Load(defaultVersion string) Config { @@ -65,6 +71,9 @@ func Load(defaultVersion string) Config { StaleSweepInterval: durationSeconds(envSweepSeconds, 15*time.Second), CreditHold: durationSeconds(envCreditHoldSeconds, 24*time.Hour), RequesterRegionHeader: getenv(envRequesterRegionHeader, "X-Geo-Region"), + CairoHost: os.Getenv(envCairoHost), + CairoWriteKey: os.Getenv(envCairoWriteKey), + CairoNamespace: getenv(envCairoNamespace, "default"), Alerts: operatorstore.AlertConfig{ DisconnectSpikeWindow: alerts.DisconnectSpikeWindow, DisconnectSpikeThreshold: intEnv(envAlertDisconnects, alerts.DisconnectSpikeThreshold), diff --git a/internal/coordinator/httpapi/health.go b/internal/coordinator/httpapi/health.go index 980e7d6..bbae660 100644 --- a/internal/coordinator/httpapi/health.go +++ b/internal/coordinator/httpapi/health.go @@ -15,6 +15,7 @@ import ( "time" "github.com/Ani-HQ/thirdshift/internal/coordinator/auth" + "github.com/Ani-HQ/thirdshift/internal/coordinator/cairo" "github.com/Ani-HQ/thirdshift/internal/coordinator/jobs" operatorstore "github.com/Ani-HQ/thirdshift/internal/coordinator/operator" "github.com/Ani-HQ/thirdshift/internal/coordinator/registration" @@ -44,6 +45,7 @@ type Options struct { StatusCacheTTL time.Duration RequesterRegionHeader string WaitlistLimitPerMinute int + Cairo *cairo.Tracker Now func() time.Time Logger *slog.Logger } diff --git a/internal/coordinator/httpapi/waitlist.go b/internal/coordinator/httpapi/waitlist.go index 73cb2e2..d2d398e 100644 --- a/internal/coordinator/httpapi/waitlist.go +++ b/internal/coordinator/httpapi/waitlist.go @@ -116,10 +116,21 @@ func (o Options) waitlistSignupHandler(limiter *waitlistRateLimiter) http.Handle writeError(w, http.StatusTooManyRequests, "waitlist signup rate limit exceeded") return } - if _, _, err := store.SubmitWaitlistApplication(r.Context(), application, o.now()); err != nil { + _, inserted, err := store.SubmitWaitlistApplication(r.Context(), application, o.now()) + if err != nil { writeError(w, http.StatusInternalServerError, err.Error()) return } + if o.Cairo != nil { + o.Cairo.NotifyAccessApplicationAsync(application.Email, map[string]any{ + "name": application.Name, + "use_case": application.UseCase, + "expected_volume": application.ExpectedVolume, + "model_id": application.ModelID, + "source": application.Source, + "is_new": inserted, + }) + } writeJSON(w, http.StatusOK, response{Status: "ok"}) } }