Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix: gzip daemon claim responses (#4259)

Bohan Jiang2f398c36ada1
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 3ba8cb455a..779e9679fa 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -101,6 +101,20 @@ func NewRouter(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus, analytics
return r
}
+func daemonJSONCompressor() func(http.Handler) http.Handler {
+ compress := chimw.Compress(5, "application/json")
+ return func(next http.Handler) http.Handler {
+ compressed := compress(next)
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if strings.EqualFold(r.Header.Get("Upgrade"), "websocket") {
+ next.ServeHTTP(w, r)
+ return
+ }
+ compressed.ServeHTTP(w, r)
+ })
+ }
+}
+
type RouterOptions struct {
HTTPMetrics *obsmetrics.HTTPMetrics
BusinessMetrics *obsmetrics.BusinessMetrics
@@ -494,6 +508,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// Daemon API routes (require daemon token or valid user token)
r.Route("/api/daemon", func(r chi.Router) {
r.Use(middleware.DaemonAuth(queries, patCache, daemonTokenCache, cloudPATVerifier))
+ r.Use(daemonJSONCompressor())
r.Post("/register", h.DaemonRegister)
r.Post("/deregister", h.DaemonDeregister)
diff --git a/server/cmd/server/router_compression_test.go b/server/cmd/server/router_compression_test.go
new file mode 100644
index 0000000000..e8116fcb59
--- /dev/null
+++ b/server/cmd/server/router_compression_test.go
@@ -0,0 +1,92 @@
+package main
+
+import (
+ "compress/gzip"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/go-chi/chi/v5"
+)
+
+func TestDaemonJSONCompressorGzipsJSONWhenAccepted(t *testing.T) {
+ router := chi.NewRouter()
+ router.Use(daemonJSONCompressor())
+ router.Get("/api/daemon/test", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ w.Write([]byte(`{"payload":"` + strings.Repeat("x", 256) + `"}`))
+ })
+
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodGet, "/api/daemon/test", nil)
+ req.Header.Set("Accept-Encoding", "gzip")
+ router.ServeHTTP(rec, req)
+
+ if got := rec.Header().Get("Content-Encoding"); got != "gzip" {
+ t.Fatalf("Content-Encoding = %q, want gzip", got)
+ }
+ if got := rec.Header().Get("Vary"); got != "Accept-Encoding" {
+ t.Fatalf("Vary = %q, want Accept-Encoding", got)
+ }
+
+ zr, err := gzip.NewReader(rec.Body)
+ if err != nil {
+ t.Fatalf("open gzip body: %v", err)
+ }
+ defer zr.Close()
+ body, err := io.ReadAll(zr)
+ if err != nil {
+ t.Fatalf("read gzip body: %v", err)
+ }
+ if !strings.Contains(string(body), `"payload":"xxx`) {
+ t.Fatalf("decoded body missing payload: %s", string(body))
+ }
+}
+
+func TestDaemonJSONCompressorLeavesPlainJSONWhenGzipNotAccepted(t *testing.T) {
+ router := chi.NewRouter()
+ router.Use(daemonJSONCompressor())
+ router.Get("/api/daemon/test", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ w.Write([]byte(`{"task":null}`))
+ })
+
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodGet, "/api/daemon/test", nil)
+ router.ServeHTTP(rec, req)
+
+ if got := rec.Header().Get("Content-Encoding"); got != "" {
+ t.Fatalf("Content-Encoding = %q, want empty", got)
+ }
+ if got := rec.Body.String(); got != `{"task":null}` {
+ t.Fatalf("body = %q, want plain JSON", got)
+ }
+}
+
+func TestDaemonJSONCompressorSkipsWebsocketUpgrade(t *testing.T) {
+ router := chi.NewRouter()
+ router.Use(daemonJSONCompressor())
+ router.Get("/api/daemon/ws", func(w http.ResponseWriter, r *http.Request) {
+ if got := r.Header.Get("Upgrade"); got != "websocket" {
+ t.Fatalf("Upgrade header = %q, want websocket", got)
+ }
+ w.WriteHeader(http.StatusSwitchingProtocols)
+ })
+
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodGet, "/api/daemon/ws", nil)
+ req.Header.Set("Accept-Encoding", "gzip")
+ req.Header.Set("Connection", "Upgrade")
+ req.Header.Set("Upgrade", "websocket")
+ router.ServeHTTP(rec, req)
+
+ if got := rec.Header().Get("Content-Encoding"); got != "" {
+ t.Fatalf("Content-Encoding = %q, want empty for websocket upgrade", got)
+ }
+ if rec.Code != http.StatusSwitchingProtocols {
+ t.Fatalf("status = %d, want %d", rec.Code, http.StatusSwitchingProtocols)
+ }
+}
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 95c89f8268..abea25ad45 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -1128,7 +1128,7 @@ func logHeartbeatEndpointSlow(runtimeID, outcome, authPath string, start time.Ti
// logClaimEndpointSlow emits one structured log when the /tasks/claim endpoint
// exceeds 500ms, splitting auth / claim / response-build phases so the prod
// tail can be diagnosed without flooding logs at normal poll rates.
-func logClaimEndpointSlow(runtimeID, outcome string, start time.Time, authMs, claimMs, buildMs int64) {
+func logClaimEndpointSlow(runtimeID, outcome string, start time.Time, authMs, claimMs, buildMs int64, payloadBytes, agentSkillCount, builtinSkillCount, skillPayloadBytes int) {
totalMs := time.Since(start).Milliseconds()
if totalMs < 500 {
return
@@ -1140,6 +1140,10 @@ func logClaimEndpointSlow(runtimeID, outcome string, start time.Time, authMs, cl
"auth_ms", authMs,
"claim_ms", claimMs,
"build_ms", buildMs,
+ "payload_bytes", payloadBytes,
+ "agent_skill_count", agentSkillCount,
+ "builtin_skill_count", builtinSkillCount,
+ "skill_payload_bytes", skillPayloadBytes,
)
}
@@ -1152,6 +1156,10 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
var (
outcome = "unauth"
authMs, claimMs, buildMs int64
+ payloadBytes int
+ agentSkillCount int
+ builtinSkillCount int
+ skillPayloadBytes int
buildStart time.Time
)
defer func() {
@@ -1161,7 +1169,7 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
if !buildStart.IsZero() {
buildMs = time.Since(buildStart).Milliseconds()
}
- logClaimEndpointSlow(runtimeID, outcome, start, authMs, claimMs, buildMs)
+ logClaimEndpointSlow(runtimeID, outcome, start, authMs, claimMs, buildMs, payloadBytes, agentSkillCount, builtinSkillCount, skillPayloadBytes)
}()
// Verify the caller owns this runtime's workspace. The runtime's
@@ -1187,7 +1195,7 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
if task == nil {
slog.Debug("no task to claim", "runtime_id", runtimeID)
- writeJSON(w, http.StatusOK, map[string]any{"task": nil})
+ payloadBytes, _ = writeMeasuredJSON(w, http.StatusOK, map[string]any{"task": nil})
outcome = "no_task"
return
}
@@ -1202,7 +1210,10 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
// names carry a "multica-" prefix so their on-disk slugs never collide
// with a user-authored workspace skill (see writeSkillFiles).
skills := h.TaskService.LoadAgentSkills(r.Context(), task.AgentID)
- skills = append(skills, h.TaskService.BuiltinSkills()...)
+ agentSkillCount = len(skills)
+ builtinSkills := h.TaskService.BuiltinSkills()
+ builtinSkillCount = len(builtinSkills)
+ skills = append(skills, builtinSkills...)
var customEnv map[string]string
if agent.CustomEnv != nil {
if err := json.Unmarshal(agent.CustomEnv, &customEnv); err != nil {
@@ -1793,7 +1804,12 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
resp.AuthToken = tokenStr
slog.Info("task claimed by runtime", "task_id", uuidToString(task.ID), "runtime_id", runtimeID, "agent_id", uuidToString(task.AgentID), "prior_session", resp.PriorSessionID)
- writeJSON(w, http.StatusOK, map[string]any{"task": resp})
+ if resp.Agent != nil && len(resp.Agent.Skills) > 0 {
+ if skillPayload, err := json.Marshal(resp.Agent.Skills); err == nil {
+ skillPayloadBytes = len(skillPayload)
+ }
+ }
+ payloadBytes, _ = writeMeasuredJSON(w, http.StatusOK, map[string]any{"task": resp})
}
// trailingUserMessages returns the run of user messages after the last
diff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.go
index cffbc82a9a..d41c746b12 100644
--- a/server/internal/handler/daemon_test.go
+++ b/server/internal/handler/daemon_test.go
@@ -6,6 +6,7 @@ import (
"encoding/json"
"errors"
"fmt"
+ "log/slog"
"net/http"
"net/http/httptest"
"strings"
@@ -22,6 +23,29 @@ import (
"github.com/multica-ai/multica/server/pkg/protocol"
)
+func TestLogClaimEndpointSlowIncludesPayloadFields(t *testing.T) {
+ var logs bytes.Buffer
+ prev := slog.Default()
+ slog.SetDefault(slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelInfo})))
+ t.Cleanup(func() { slog.SetDefault(prev) })
+
+ logClaimEndpointSlow("runtime-1", "claimed", time.Now().Add(-600*time.Millisecond), 10, 20, 30, 4096, 2, 8, 3072)
+
+ got := logs.String()
+ for _, want := range []string{
+ "msg=\"claim_endpoint slow\"",
+ "runtime_id=runtime-1",
+ "payload_bytes=4096",
+ "agent_skill_count=2",
+ "builtin_skill_count=8",
+ "skill_payload_bytes=3072",
+ } {
+ if !strings.Contains(got, want) {
+ t.Fatalf("slow claim log missing %q in %s", want, got)
+ }
+ }
+}
+
// slowProbeLocalSkillListStore wraps a LocalSkillListStore but blocks inside
// HasPending until the provided context is cancelled. PopPending delegates
// to the underlying store. Used to verify that a stalled probe cannot wedge
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index dd66ad51ba..40f8092383 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -230,6 +230,21 @@ func writeJSON(w http.ResponseWriter, status int, v any) {
json.NewEncoder(w).Encode(v)
}
+func writeMeasuredJSON(w http.ResponseWriter, status int, v any) (int, error) {
+ body, err := json.Marshal(v)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to encode response")
+ return 0, err
+ }
+ body = append(body, '\n')
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(status)
+ if _, err := w.Write(body); err != nil {
+ return len(body), err
+ }
+ return len(body), nil
+}
+
func writeError(w http.ResponseWriter, status int, msg string) {
writeJSON(w, status, map[string]string{"error": msg})
}