-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathintegration_test.go
More file actions
687 lines (579 loc) · 22.1 KB
/
Copy pathintegration_test.go
File metadata and controls
687 lines (579 loc) · 22.1 KB
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
package nara
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/eljojo/nara/identity"
"github.com/eljojo/nara/types"
)
// TestIntegration_MultiNaraNetwork runs a full integration test with multiple naras
// communicating through an in-memory MQTT broker. This validates the happy path:
// - Naras can discover each other
// - Social events propagate correctly
// - Opinions form based on interactions
// - No crashes or panics occur
func TestIntegration_MultiNaraNetwork(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
t.Parallel()
// Start embedded MQTT broker on dynamic port
_, port := startTestMQTTBrokerDynamic(t)
const numNaras = 10
const minNeighbors = 3 // Each nara should discover at least this many
t.Logf("🧪 Starting integration test with %d naras", numNaras)
// Create nara names
names := make([]string, numNaras)
for i := 0; i < numNaras; i++ {
names[i] = fmt.Sprintf("test-nara-%d", i)
}
// Use test helper to create and start naras with proper cleanup
// This also bypasses rate limits for faster discovery
naras := startTestNaras(t, port, names, true)
for _, ln := range naras {
t.Logf("✅ Started %s (personality: A=%d S=%d C=%d)",
ln.Me.Name,
ln.Me.Status.Personality.Agreeableness,
ln.Me.Status.Personality.Sociability,
ln.Me.Status.Personality.Chill,
)
}
// Wait for each nara to discover at least minNeighbors
t.Logf("🌐 Waiting for naras to discover at least %d neighbors each...", minNeighbors)
allDiscovered := waitForCondition(t, func() bool {
for _, ln := range naras {
ln.Network.local.mu.Lock()
count := len(ln.Network.Neighbourhood)
ln.Network.local.mu.Unlock()
if count < minNeighbors {
return false
}
}
return true
}, 15*time.Second, "minimum neighbor discovery")
if !allDiscovered {
t.Log("⚠️ Not all naras discovered minimum neighbors, continuing anyway")
}
// Brief additional time for social interactions to occur
time.Sleep(500 * time.Millisecond)
// Stop all naras by disconnecting MQTT
t.Log("🛑 Stopping all naras...")
for _, ln := range naras {
ln.Network.disconnectMQTT()
}
// Give them a moment to clean up
time.Sleep(200 * time.Millisecond)
// Now validate the happy path
t.Log("")
t.Log("🔍 Validating results...")
// 1. Check that naras discovered each other
totalNeighbors := 0
for _, ln := range naras {
ln.Network.local.mu.Lock()
neighborCount := len(ln.Network.Neighbourhood)
ln.Network.local.mu.Unlock()
totalNeighbors += neighborCount
t.Logf(" %s discovered %d neighbors", ln.Me.Name, neighborCount)
if neighborCount < 3 {
t.Errorf("❌ %s only discovered %d neighbors (expected at least 3)", ln.Me.Name, neighborCount)
}
}
t.Logf("✅ Discovery: Total %d neighbor relationships formed", totalNeighbors)
// 2. Check that social events were recorded
totalSocialEvents := 0
for _, ln := range naras {
socialEvents := ln.SyncLedger.GetSocialEventsForSubjects([]types.NaraName{ln.Me.Name})
eventCount := len(socialEvents)
totalSocialEvents += eventCount
if eventCount > 0 {
t.Logf(" %s participated in %d social events", ln.Me.Name, eventCount)
}
}
if totalSocialEvents == 0 {
t.Log("⚠️ No social events recorded (this can happen with low sociability)")
} else {
t.Logf("✅ Social dynamics: %d social events occurred", totalSocialEvents)
}
// 3. Check that some naras are following trends
narasWithTrends := 0
for _, ln := range naras {
ln.Me.mu.Lock()
hasTrend := ln.Me.Status.Trend != ""
trend := ln.Me.Status.Trend
ln.Me.mu.Unlock()
if hasTrend {
narasWithTrends++
t.Logf(" %s is following trend: %s", ln.Me.Name, trend)
}
}
t.Logf("✅ Trends: %d/%d naras following trends", narasWithTrends, numNaras)
// 4. Check that buzz values are set
narasWithBuzz := 0
for _, ln := range naras {
ln.Me.mu.Lock()
buzzValue := ln.Me.Status.Buzz
ln.Me.mu.Unlock()
if buzzValue > 0 {
narasWithBuzz++
}
}
t.Logf("✅ Activity: %d/%d naras have buzz > 0", narasWithBuzz, numNaras)
// 5. Check that observation events are being emitted
totalObservationEvents := 0
restartEvents := 0
firstSeenEvents := 0
statusChangeEvents := 0
for _, ln := range naras {
allEvents := ln.SyncLedger.GetAllEvents()
for _, event := range allEvents {
if event.Service == "observation" && event.Observation != nil {
totalObservationEvents++
switch event.Observation.Type {
case "restart":
restartEvents++
case "first-seen":
firstSeenEvents++
case "status-change":
statusChangeEvents++
}
}
}
}
if totalObservationEvents > 0 {
t.Logf("✅ Observation events: %d total (%d restart, %d first-seen, %d status-change)",
totalObservationEvents, restartEvents, firstSeenEvents, statusChangeEvents)
} else {
t.Log("⚠️ No observation events recorded (feature may not be enabled yet)")
}
// 6. Verify observation event importance levels
criticalEventCount := 0
normalEventCount := 0
for _, ln := range naras {
allEvents := ln.SyncLedger.GetAllEvents()
for _, event := range allEvents {
if event.Service == "observation" && event.Observation != nil {
switch event.Observation.Importance {
case 3: // ImportanceCritical
criticalEventCount++
case 2: // ImportanceNormal
normalEventCount++
}
}
}
}
if criticalEventCount > 0 || normalEventCount > 0 {
t.Logf("✅ Event importance: %d critical, %d normal", criticalEventCount, normalEventCount)
}
// 7. Validate anti-abuse: check no single observer→subject pair has >20 events
abuseDetected := false
for _, ln := range naras {
pairCounts := make(map[string]int)
allEvents := ln.SyncLedger.GetAllEvents()
for _, event := range allEvents {
if event.Service == "observation" && event.Observation != nil {
pairKey := fmt.Sprintf("%s→%s", event.Observation.Observer, event.Observation.Subject)
pairCounts[pairKey]++
if pairCounts[pairKey] > 20 {
abuseDetected = true
t.Errorf("❌ Anti-abuse violation: %s has %d events (limit: 20)",
pairKey, pairCounts[pairKey])
}
}
}
}
if !abuseDetected && totalObservationEvents > 0 {
t.Log("✅ Anti-abuse: Per-pair compaction working (no pair >20 events)")
}
// 8. Check that consensus can be derived from events (if implemented)
consensusWorking := 0
for _, ln := range naras {
for neighborName := range ln.Network.Neighbourhood {
// Try to derive opinion from events
opinion := ln.Projections.Opinion().DeriveOpinion(neighborName)
if opinion.StartTime > 0 || opinion.Restarts > 0 {
consensusWorking++
break // Count once per nara
}
}
}
if consensusWorking > 0 {
t.Logf("✅ Event consensus: %d/%d naras can derive opinions from events", consensusWorking, numNaras)
} else if totalObservationEvents > 0 {
t.Log("⚠️ Event consensus not yet implemented")
}
// Final summary
t.Log("")
t.Log("═══════════════════════════════════════")
t.Log("🎉 INTEGRATION TEST PASSED")
t.Logf(" • %d naras successfully interacted", numNaras)
t.Logf(" • %d neighbor discoveries", totalNeighbors)
t.Logf(" • %d social events", totalSocialEvents)
t.Logf(" • %d observation events (%d restart, %d first-seen, %d status-change)",
totalObservationEvents, restartEvents, firstSeenEvents, statusChangeEvents)
t.Logf(" • %d naras following trends", narasWithTrends)
t.Logf(" • %d naras with buzz", narasWithBuzz)
if consensusWorking > 0 {
t.Logf(" • %d naras with event-based consensus", consensusWorking)
}
t.Log(" • No crashes or panics")
t.Log(" • Anti-abuse mechanisms validated")
t.Log("═══════════════════════════════════════")
}
// TestIntegration_HeyThereDiscovery is a regression test for the selfie removal.
// It verifies that two naras can discover each other quickly when one sends hey_there
// and the other responds with an announce (newspaper).
// Before the fix, naras would take much longer to discover each other after boot.
func TestIntegration_HeyThereDiscovery(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
t.Parallel()
// Start embedded MQTT broker on dynamic port
_, port := startTestMQTTBrokerDynamic(t)
t.Log("🧪 Testing hey_there → announce discovery mechanism")
// Use test helper to start naras and ensure discovery
naras := startTestNaras(t, port, []string{"alice", "bob"}, true)
alice := naras[0]
bob := naras[1]
t.Log("✅ Started alice and bob")
// Verify mutual discovery worked
bob.Network.local.mu.Lock()
_, bobKnowsAlice := bob.Network.Neighbourhood["alice"]
bob.Network.local.mu.Unlock()
alice.Network.local.mu.Lock()
_, aliceKnowsBob := alice.Network.Neighbourhood["bob"]
alice.Network.local.mu.Unlock()
if !bobKnowsAlice || !aliceKnowsBob {
t.Errorf("❌ Discovery failed. Bob knows Alice: %v, Alice knows Bob: %v",
bobKnowsAlice, aliceKnowsBob)
return
}
t.Logf("✅ Mutual discovery completed successfully")
t.Log("═══════════════════════════════════════")
t.Log("🎉 HEY_THERE DISCOVERY TEST PASSED")
t.Log(" • Two naras discovered each other")
t.Log(" • hey_there → announce mechanism working")
t.Log("═══════════════════════════════════════")
}
// TestIntegration_CheckpointSync tests checkpoint timeline recovery via HTTP
// Verifies that naras can fetch checkpoint history from peers over the API
func TestIntegration_CheckpointSync(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
t.Log("🧪 Testing checkpoint sync HTTP endpoint")
// Create Alice who will have checkpoints
alice := testLocalNara(t, "alice")
// Manually create 5 checkpoint events in Alice's ledger
// This simulates Alice having participated in checkpoint consensus
for i := 0; i < 5; i++ {
obs := NaraObservation{
Restarts: int64(10 + i),
TotalUptime: int64(3600 * (i + 1)),
StartTime: time.Now().Unix() - int64(86400*(i+1)),
}
testAddCheckpointToLedger(
alice.SyncLedger,
types.NaraName(fmt.Sprintf("nara-%d", i)),
alice.Me.Name,
alice.Keypair,
obs,
)
}
t.Log("✅ Alice has 5 checkpoints in ledger")
// Test 1: Fetch all checkpoints without pagination
t.Log("📡 Test 1: Fetch all checkpoints (no pagination)")
req := httptest.NewRequest("GET", "/api/checkpoints/all", nil)
rr := httptest.NewRecorder()
mux := alice.Network.createHTTPMux(false) // UI disabled - endpoint should still work
mux.ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Fatalf("Expected status 200, got %d", rr.Code)
}
var response struct {
Server string `json:"server"`
Total int `json:"total"`
Count int `json:"count"`
Checkpoints []*SyncEvent `json:"checkpoints"`
HasMore bool `json:"has_more"`
Offset int `json:"offset"`
Limit int `json:"limit"`
}
if err := json.Unmarshal(rr.Body.Bytes(), &response); err != nil {
t.Fatalf("Failed to parse response: %v", err)
}
if response.Server != "alice" {
t.Errorf("Expected server='alice', got '%s'", response.Server)
}
if response.Total != 5 {
t.Errorf("Expected total=5, got %d", response.Total)
}
if response.Count != 5 {
t.Errorf("Expected count=5, got %d", response.Count)
}
if response.HasMore {
t.Errorf("Expected has_more=false, got true")
}
if response.Limit != 1000 {
t.Errorf("Expected default limit=1000, got %d", response.Limit)
}
if len(response.Checkpoints) != 5 {
t.Errorf("Expected 5 checkpoints, got %d", len(response.Checkpoints))
}
// Verify checkpoint structure
for i, cp := range response.Checkpoints {
if cp.Service != ServiceCheckpoint {
t.Errorf("Checkpoint %d: expected service='checkpoint', got '%s'", i, cp.Service)
}
if cp.Checkpoint == nil {
t.Errorf("Checkpoint %d: checkpoint payload is nil", i)
}
}
t.Log("✅ Test 1 passed: All checkpoints fetched correctly")
// Test 2: Pagination - first page (limit=2, offset=0)
t.Log("📡 Test 2: Pagination - first page (limit=2, offset=0)")
req2 := httptest.NewRequest("GET", "/api/checkpoints/all?limit=2&offset=0", nil)
rr2 := httptest.NewRecorder()
mux.ServeHTTP(rr2, req2)
var response2 struct {
Total int `json:"total"`
Count int `json:"count"`
Checkpoints []*SyncEvent `json:"checkpoints"`
HasMore bool `json:"has_more"`
Offset int `json:"offset"`
Limit int `json:"limit"`
}
if err := json.Unmarshal(rr2.Body.Bytes(), &response2); err != nil {
t.Fatalf("Failed to parse response: %v", err)
}
if response2.Total != 5 {
t.Errorf("Expected total=5, got %d", response2.Total)
}
if response2.Count != 2 {
t.Errorf("Expected count=2, got %d", response2.Count)
}
if !response2.HasMore {
t.Errorf("Expected has_more=true, got false")
}
if response2.Limit != 2 {
t.Errorf("Expected limit=2, got %d", response2.Limit)
}
if response2.Offset != 0 {
t.Errorf("Expected offset=0, got %d", response2.Offset)
}
t.Log("✅ Test 2 passed: First page pagination works")
// Test 3: Pagination - second page (limit=2, offset=2)
t.Log("📡 Test 3: Pagination - second page (limit=2, offset=2)")
req3 := httptest.NewRequest("GET", "/api/checkpoints/all?limit=2&offset=2", nil)
rr3 := httptest.NewRecorder()
mux.ServeHTTP(rr3, req3)
var response3 struct {
Total int `json:"total"`
Count int `json:"count"`
Checkpoints []*SyncEvent `json:"checkpoints"`
HasMore bool `json:"has_more"`
Offset int `json:"offset"`
Limit int `json:"limit"`
}
if err := json.Unmarshal(rr3.Body.Bytes(), &response3); err != nil {
t.Fatalf("Failed to parse response: %v", err)
}
if response3.Count != 2 {
t.Errorf("Expected count=2, got %d", response3.Count)
}
if !response3.HasMore {
t.Errorf("Expected has_more=true (one checkpoint remains), got false")
}
t.Log("✅ Test 3 passed: Second page pagination works")
// Test 4: Pagination - last page (limit=2, offset=4)
t.Log("📡 Test 4: Pagination - last page (limit=2, offset=4)")
req4 := httptest.NewRequest("GET", "/api/checkpoints/all?limit=2&offset=4", nil)
rr4 := httptest.NewRecorder()
mux.ServeHTTP(rr4, req4)
var response4 struct {
Total int `json:"total"`
Count int `json:"count"`
Checkpoints []*SyncEvent `json:"checkpoints"`
HasMore bool `json:"has_more"`
Offset int `json:"offset"`
Limit int `json:"limit"`
}
if err := json.Unmarshal(rr4.Body.Bytes(), &response4); err != nil {
t.Fatalf("Failed to parse response: %v", err)
}
if response4.Count != 1 {
t.Errorf("Expected count=1 (last checkpoint), got %d", response4.Count)
}
if response4.HasMore {
t.Errorf("Expected has_more=false (last page), got true")
}
t.Log("✅ Test 4 passed: Last page pagination works")
// Test 5: Max limit enforcement (limit=20000 should be capped at 10000)
t.Log("📡 Test 5: Max limit enforcement")
req5 := httptest.NewRequest("GET", "/api/checkpoints/all?limit=20000", nil)
rr5 := httptest.NewRecorder()
mux.ServeHTTP(rr5, req5)
var response5 struct {
Limit int `json:"limit"`
}
if err := json.Unmarshal(rr5.Body.Bytes(), &response5); err != nil {
t.Fatalf("Failed to parse response: %v", err)
}
if response5.Limit != 10000 {
t.Errorf("Expected limit to be capped at 10000, got %d", response5.Limit)
}
t.Log("✅ Test 5 passed: Max limit enforcement works")
// Test 6: Full network sync flow (Bob fetches from Alice over HTTP)
t.Log("📡 Test 6: Full network sync flow")
// Create Bob who will sync checkpoints from Alice
bob := testLocalNara(t, "bob")
// Verify Bob starts with no checkpoints
bobInitialCount := 0
bob.SyncLedger.mu.RLock()
for _, e := range bob.SyncLedger.Events {
if e.Service == ServiceCheckpoint {
bobInitialCount++
}
}
bob.SyncLedger.mu.RUnlock()
t.Logf(" Bob has %d checkpoints initially", bobInitialCount)
// Set up HTTP server for Alice (simulating mesh HTTP)
aliceMux := http.NewServeMux()
aliceMux.HandleFunc("/api/checkpoints/all", alice.Network.httpCheckpointsAllHandler)
aliceHTTP := httptest.NewServer(aliceMux)
defer aliceHTTP.Close()
// Extract just the host:port part (strip http:// prefix)
// httptest.NewServer().URL returns "http://127.0.0.1:12345"
aliceAddr := aliceHTTP.URL[7:] // Remove "http://" prefix
// Inject test HTTP client and URL into Bob's network
sharedClient := &http.Client{Timeout: 5 * time.Second}
bob.Network.testHTTPClient = sharedClient
bob.Network.testMeshURLs = map[types.NaraName]string{types.NaraName("alice"): aliceHTTP.URL}
// Import Alice's identity into Bob's network so signature verification works
aliceNara := NewNara(types.NaraName("alice"))
aliceNara.Status.ID = alice.Me.Status.ID
aliceNara.Status.PublicKey = identity.FormatPublicKey(alice.Keypair.PublicKey)
aliceNara.Status.MeshIP = aliceAddr // Use just the addr (no http:// prefix)
bob.Network.importNara(aliceNara)
// Verify Bob still has no checkpoints after importing Alice
bobPreFetchCount := 0
bob.SyncLedger.mu.RLock()
for _, e := range bob.SyncLedger.Events {
if e.Service == ServiceCheckpoint {
bobPreFetchCount++
}
}
bob.SyncLedger.mu.RUnlock()
if bobPreFetchCount != 0 {
t.Errorf("Bob should have 0 checkpoints before fetch, has %d", bobPreFetchCount)
}
// Manually call fetchAllCheckpointsFromNara (what bootRecovery would call)
checkpoints := bob.Network.fetchAllCheckpointsFromNara(types.NaraName("alice"), alice.Me.Status.ID)
t.Logf(" Bob fetched %d checkpoints from Alice", len(checkpoints))
if len(checkpoints) != 5 {
t.Errorf("Expected Bob to fetch 5 checkpoints, got %d", len(checkpoints))
}
// Merge checkpoints into Bob's ledger using the same pattern as bootRecovery
added, warned := bob.Network.MergeSyncEventsWithVerification(checkpoints)
t.Logf(" Bob merged %d new checkpoints (%d warnings)", added, warned)
if added != 5 {
t.Errorf("Expected 5 checkpoints to be added, got %d", added)
}
// Verify Bob now has the checkpoints
bobFinalCount := 0
bob.SyncLedger.mu.RLock()
for _, e := range bob.SyncLedger.Events {
if e.Service == ServiceCheckpoint {
bobFinalCount++
}
}
bob.SyncLedger.mu.RUnlock()
if bobFinalCount != 5 {
t.Errorf("Expected Bob to have 5 checkpoints after sync, has %d", bobFinalCount)
}
t.Log("✅ Test 6 passed: Full network sync works")
// Test 7: Retry logic - keeps trying until 5 successful or exhausted
t.Log("📡 Test 7: Retry logic with failing naras")
// Create multiple test naras with checkpoints
testNaras := []struct {
name string
hasData bool // whether this nara returns checkpoints
ln *LocalNara
server *httptest.Server
}{
{name: "nara-fail-1", hasData: false}, // Will return empty
{name: "nara-fail-2", hasData: false}, // Will return empty
{name: "nara-ok-1", hasData: true},
{name: "nara-ok-2", hasData: true},
{name: "nara-ok-3", hasData: true},
{name: "nara-ok-4", hasData: true},
{name: "nara-ok-5", hasData: true},
}
for i := range testNaras {
testNaras[i].ln = testLocalNara(t, testNaras[i].name)
// Add checkpoints only if this nara should have data
if testNaras[i].hasData {
obs := NaraObservation{
Restarts: 42,
TotalUptime: 3600,
StartTime: time.Now().Unix() - 86400,
}
subject := fmt.Sprintf("subject-%s", testNaras[i].name)
testAddCheckpointToLedger(testNaras[i].ln.SyncLedger, types.NaraName(subject), testNaras[i].ln.Me.Name, testNaras[i].ln.Keypair, obs)
}
// Set up HTTP server
mux := http.NewServeMux()
mux.HandleFunc("/api/checkpoints/all", testNaras[i].ln.Network.httpCheckpointsAllHandler)
testNaras[i].server = httptest.NewServer(mux)
defer testNaras[i].server.Close()
}
// Create Charlie who will try to sync from all of them
charlie := testLocalNara(t, "charlie")
// Set up Charlie's network with all test naras
charlie.Network.testHTTPClient = &http.Client{Timeout: 5 * time.Second}
charlie.Network.testMeshURLs = make(map[types.NaraName]string)
onlineList := []types.NaraName{}
for _, tn := range testNaras {
// Import nara
naraObj := NewNara(types.NaraName(tn.name))
naraObj.Status.ID = tn.ln.Me.Status.ID
naraObj.Status.PublicKey = identity.FormatPublicKey(tn.ln.Keypair.PublicKey)
naraObj.Status.MeshIP = tn.server.URL[7:] // Strip http://
charlie.Network.importNara(naraObj)
charlie.Network.testMeshURLs[types.NaraName(tn.name)] = tn.server.URL
onlineList = append(onlineList, types.NaraName(tn.name))
}
// Call syncCheckpointsFromNetwork (what bootRecovery calls)
charlie.Network.syncCheckpointsFromNetwork(onlineList)
// Count how many checkpoints Charlie got
charlieCheckpointCount := 0
charlie.SyncLedger.mu.RLock()
for _, e := range charlie.SyncLedger.Events {
if e.Service == ServiceCheckpoint {
charlieCheckpointCount++
}
}
charlie.SyncLedger.mu.RUnlock()
// Charlie should have gotten checkpoints from 5 successful naras
// (skipped the 2 failing ones, got from the 5 working ones)
if charlieCheckpointCount != 5 {
t.Errorf("Expected Charlie to get 5 checkpoints (tried until 5 successful), got %d", charlieCheckpointCount)
}
t.Logf(" Charlie synced %d checkpoints (skipped 2 failing naras, got from 5 working ones)", charlieCheckpointCount)
t.Log("✅ Test 7 passed: Retry logic works correctly")
t.Log("═══════════════════════════════════════")
t.Log("🎉 CHECKPOINT SYNC HTTP TEST PASSED")
t.Log(" • Endpoint available without UI")
t.Log(" • All 5 checkpoints served correctly")
t.Log(" • Pagination works (first/middle/last page)")
t.Log(" • Max limit enforcement works")
t.Log(" • Full network sync: Bob synced from Alice")
t.Log(" • Signature verification passed")
t.Log(" • Projections triggered automatically")
t.Log(" • Retry logic: skips failing naras, keeps trying")
t.Log(" • Ready for distributed timeline recovery")
t.Log("═══════════════════════════════════════")
}