aboutsummaryrefslogtreecommitdiff
path: root/test/kafka/integration/schema_registry_test.go
blob: 9f6d32849d25c30d0f5449b73b1ced593a7bc82b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
package integration

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strings"
	"testing"
	"time"

	"github.com/seaweedfs/seaweedfs/test/kafka/internal/testutil"
)

// TestSchemaRegistryEventualConsistency reproduces the issue where schemas
// are registered successfully but are not immediately queryable due to
// Schema Registry's consumer lag
func TestSchemaRegistryEventualConsistency(t *testing.T) {
	// This test requires real SMQ backend
	gateway := testutil.NewGatewayTestServerWithSMQ(t, testutil.SMQRequired)
	defer gateway.CleanupAndClose()

	addr := gateway.StartAndWait()
	t.Logf("Gateway running on %s", addr)

	// Schema Registry URL from environment or default
	schemaRegistryURL := "http://localhost:8081"

	// Wait for Schema Registry to be ready
	if !waitForSchemaRegistry(t, schemaRegistryURL, 30*time.Second) {
		t.Fatal("Schema Registry not ready")
	}

	// Define test schemas
	valueSchema := `{"type":"record","name":"TestMessage","fields":[{"name":"id","type":"string"}]}`
	keySchema := `{"type":"string"}`

	// Register multiple schemas rapidly (simulates the load test scenario)
	subjects := []string{
		"test-topic-0-value",
		"test-topic-0-key",
		"test-topic-1-value",
		"test-topic-1-key",
		"test-topic-2-value",
		"test-topic-2-key",
		"test-topic-3-value",
		"test-topic-3-key",
	}

	t.Log("Registering schemas rapidly...")
	registeredIDs := make(map[string]int)
	for _, subject := range subjects {
		schema := valueSchema
		if strings.HasSuffix(subject, "-key") {
			schema = keySchema
		}

		id, err := registerSchema(schemaRegistryURL, subject, schema)
		if err != nil {
			t.Fatalf("Failed to register schema for %s: %v", subject, err)
		}
		registeredIDs[subject] = id
		t.Logf("Registered %s with ID %d", subject, id)
	}

	t.Log("All schemas registered successfully!")

	// Now immediately try to verify them (this reproduces the bug)
	t.Log("Immediately verifying schemas (without delay)...")
	immediateFailures := 0
	for _, subject := range subjects {
		exists, id, version, err := verifySchema(schemaRegistryURL, subject)
		if err != nil || !exists {
			immediateFailures++
			t.Logf("Immediate verification failed for %s: exists=%v id=%d err=%v", subject, exists, id, err)
		} else {
			t.Logf("Immediate verification passed for %s: ID=%d Version=%d", subject, id, version)
		}
	}

	if immediateFailures > 0 {
		t.Logf("BUG REPRODUCED: %d/%d schemas not immediately queryable after registration",
			immediateFailures, len(subjects))
		t.Logf("  This is due to Schema Registry's KafkaStoreReaderThread lag")
	}

	// Now verify with retry logic (this should succeed)
	t.Log("Verifying schemas with retry logic...")
	for _, subject := range subjects {
		expectedID := registeredIDs[subject]
		if !verifySchemaWithRetry(t, schemaRegistryURL, subject, expectedID, 5*time.Second) {
			t.Errorf("Failed to verify %s even with retry", subject)
		}
	}

	t.Log("✓ All schemas verified successfully with retry logic!")
}

// registerSchema registers a schema and returns its ID
func registerSchema(registryURL, subject, schema string) (int, error) {
	// Escape the schema JSON
	escapedSchema, err := json.Marshal(schema)
	if err != nil {
		return 0, err
	}

	payload := fmt.Sprintf(`{"schema":%s,"schemaType":"AVRO"}`, escapedSchema)

	resp, err := http.Post(
		fmt.Sprintf("%s/subjects/%s/versions", registryURL, subject),
		"application/vnd.schemaregistry.v1+json",
		strings.NewReader(payload),
	)
	if err != nil {
		return 0, err
	}
	defer resp.Body.Close()

	body, _ := io.ReadAll(resp.Body)

	if resp.StatusCode != http.StatusOK {
		return 0, fmt.Errorf("registration failed: %s - %s", resp.Status, string(body))
	}

	var result struct {
		ID int `json:"id"`
	}
	if err := json.Unmarshal(body, &result); err != nil {
		return 0, err
	}

	return result.ID, nil
}

// verifySchema checks if a schema exists
func verifySchema(registryURL, subject string) (exists bool, id int, version int, err error) {
	resp, err := http.Get(fmt.Sprintf("%s/subjects/%s/versions/latest", registryURL, subject))
	if err != nil {
		return false, 0, 0, err
	}
	defer resp.Body.Close()

	if resp.StatusCode == http.StatusNotFound {
		return false, 0, 0, nil
	}

	if resp.StatusCode != http.StatusOK {
		body, _ := io.ReadAll(resp.Body)
		return false, 0, 0, fmt.Errorf("verification failed: %s - %s", resp.Status, string(body))
	}

	var result struct {
		ID      int    `json:"id"`
		Version int    `json:"version"`
		Schema  string `json:"schema"`
	}
	body, _ := io.ReadAll(resp.Body)
	if err := json.Unmarshal(body, &result); err != nil {
		return false, 0, 0, err
	}

	return true, result.ID, result.Version, nil
}

// verifySchemaWithRetry verifies a schema with retry logic
func verifySchemaWithRetry(t *testing.T, registryURL, subject string, expectedID int, timeout time.Duration) bool {
	deadline := time.Now().Add(timeout)
	attempt := 0

	for time.Now().Before(deadline) {
		attempt++
		exists, id, version, err := verifySchema(registryURL, subject)

		if err == nil && exists && id == expectedID {
			if attempt > 1 {
				t.Logf("✓ %s verified after %d attempts (ID=%d, Version=%d)", subject, attempt, id, version)
			}
			return true
		}

		// Wait before retry (exponential backoff)
		waitTime := time.Duration(attempt*100) * time.Millisecond
		if waitTime > 1*time.Second {
			waitTime = 1 * time.Second
		}
		time.Sleep(waitTime)
	}

	t.Logf("%s verification timed out after %d attempts", subject, attempt)
	return false
}

// waitForSchemaRegistry waits for Schema Registry to be ready
func waitForSchemaRegistry(t *testing.T, url string, timeout time.Duration) bool {
	deadline := time.Now().Add(timeout)

	for time.Now().Before(deadline) {
		resp, err := http.Get(url + "/subjects")
		if err == nil && resp.StatusCode == http.StatusOK {
			resp.Body.Close()
			return true
		}
		if resp != nil {
			resp.Body.Close()
		}
		time.Sleep(500 * time.Millisecond)
	}

	return false
}