Files
EvoBGP/internal/nodedispatch/legacy_compatibility_test.go
DenozordecandCursor f8e0520817 feat(httpapi): harden control plane and speed up prefix refresh
Очередь job получила lease и fencing, телеметрия и прогресс deploy сохраняются, ревизия пишет manifest входов. Обновление префиксов не переписывает неизменённый снимок, большие наборы идут через COPY, а устаревшая ревизия не попадает в deploy. Бандл ноды кэшируется, prune и постановка job больше не держат горячий путь.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-02 17:23:59 +07:00

107 lines
4.7 KiB
Go

package nodedispatch_test
import (
"context"
"encoding/json"
"io"
"net/http"
"reflect"
"strings"
"testing"
"evobgp/internal/nodedispatch"
"evobgp/internal/store"
)
type legacyRoundTripFunc func(*http.Request) (*http.Response, error)
func (f legacyRoundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
func TestLegacyCompatibilityAgentSync(t *testing.T) {
for _, tc := range []struct {
name, response, wantApplied string
status int
}{
{"legacy bare success", `{"ok":true}`, "", http.StatusOK},
{"legacy empty no-content", "", "", http.StatusNoContent},
{"legacy explicit revision", `{"ok":true,"applied_revision_id":"revision-1"}`, "revision-1", http.StatusOK},
} {
t.Run(tc.name, func(t *testing.T) {
var gotAuth, gotType string
var gotBody map[string]json.RawMessage
client := &http.Client{Transport: legacyRoundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.Method != http.MethodPost || r.URL.Path != "/v1/agent/sync" {
t.Errorf("unexpected sync request: %s %s", r.Method, r.URL)
}
gotAuth, gotType = r.Header.Get("Authorization"), r.Header.Get("Content-Type")
body, _ := io.ReadAll(r.Body)
if err := json.Unmarshal(body, &gotBody); err != nil {
t.Errorf("sync JSON: %v", err)
}
return &http.Response{StatusCode: tc.status, Body: io.NopCloser(strings.NewReader(tc.response)), Header: make(http.Header)}, nil
})}
sp := &store.Speaker{ID: "speaker-1", Role: "replica", MetaJSON: store.SpeakerMetaJSON(store.SpeakerMeta{
AgentDomain: "agent.example.test", AgentSecret: "legacy-secret",
})}
got := nodedispatch.WakeSpeaker(context.Background(), sp, nodedispatch.Options{HTTPClient: client, MaxRetries: 1, RevisionID: "revision-1"})
if got.Status != "ok" || got.AppliedRevisionID != tc.wantApplied {
t.Fatalf("sync result: %+v", got)
}
wantConfirmation := "unconfirmed"
if tc.wantApplied != "" {
wantConfirmation = "agent_reported"
}
if got.Confirmation != wantConfirmation {
t.Fatalf("confirmation = %q, want %q", got.Confirmation, wantConfirmation)
}
if gotAuth != "Bearer legacy-secret" || gotType != "application/json" {
t.Fatalf("legacy headers: authorization=%q content-type=%q", gotAuth, gotType)
}
if !reflect.DeepEqual(gotBody, map[string]json.RawMessage{"revision_id": json.RawMessage(`"revision-1"`)}) {
t.Fatalf("unexpected fields sent to strict legacy decoder: %s", gotBody)
}
})
}
}
func TestAgentSyncRejectsMalformedSuccess(t *testing.T) {
for _, response := range []string{`{"ok":false}`, `{"ok":true`, `{"ok":false,"applied_revision_id":"revision-1"}`} {
t.Run(response, func(t *testing.T) {
client := &http.Client{Transport: legacyRoundTripFunc(func(*http.Request) (*http.Response, error) {
return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(response)), Header: make(http.Header)}, nil
})}
sp := &store.Speaker{ID: "speaker-1", Role: "replica", MetaJSON: store.SpeakerMetaJSON(store.SpeakerMeta{AgentDomain: "agent.example.test", AgentSecret: "secret"})}
got := nodedispatch.WakeSpeaker(context.Background(), sp, nodedispatch.Options{HTTPClient: client, MaxRetries: 1, RevisionID: "revision-1"})
if got.Status != "error" || got.AppliedRevisionID != "" {
t.Fatalf("invalid 2xx response accepted: %+v", got)
}
})
}
}
func TestLegacyCompatibilityAgentHealthMissingNewFields(t *testing.T) {
for _, tc := range []struct {
name, body, wantRevision, wantSync string
}{
{"bare legacy health", `{"ok":true}`, "", ""},
{"revision without time", `{"ok":true,"last_applied_revision_id":"revision-1"}`, "revision-1", ""},
{"revision with time", `{"ok":true,"last_applied_revision_id":"revision-1","last_sync_at":"2026-10-26T00:00:00Z"}`, "revision-1", "2026-10-26T00:00:00Z"},
} {
t.Run(tc.name, func(t *testing.T) {
client := &http.Client{Transport: legacyRoundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.Method != http.MethodGet || r.URL.Path != "/v1/agent/health" || r.Header.Get("Authorization") != "Bearer legacy-secret" {
t.Errorf("unexpected health request: %s %s", r.Method, r.URL)
}
return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(tc.body)), Header: make(http.Header)}, nil
})}
sp := &store.Speaker{ID: "speaker-1", MetaJSON: store.SpeakerMetaJSON(store.SpeakerMeta{
AgentDomain: "agent.example.test", AgentSecret: "legacy-secret",
})}
got := nodedispatch.FetchAgentHealth(context.Background(), sp, nodedispatch.Options{HTTPClient: client})
if !got.OK || got.Error != "" || got.LastAppliedRevisionID != tc.wantRevision || got.LastSyncAt != tc.wantSync {
t.Fatalf("legacy health: %+v", got)
}
})
}
}