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
|
//! Live Sync Tests
//!
//! Tests for real-time event synchronization between relays.
//! These tests verify that events published to one relay are synced
//! to another relay in real-time via the discovery mechanism.
//!
//! # Tests
//! - Test 5: `test_live_sync_layer2_events` - Layer 2 (kind 1618) events sync in real-time
//! - Test 6: `test_live_sync_layer3_events` - Layer 3 (comments) sync when referencing Layer 2
//! - Test 7: `test_live_sync_event_ordering` - Events arrive in chronological order
//!
//! # Sync Mechanism
//! These tests use the discovery-based sync pattern:
//! 1. Send announcement to both relays
//! 2. Each relay discovers the other from the announcement's relays tag
//! 3. Events sync between relays
//!
//! This tests "live" sync behavior - events syncing after connection is established,
//! as opposed to bootstrap sync which syncs existing events on startup.
use std::time::Duration;
use nostr_sdk::prelude::*;
use crate::common::{sync_helpers::*, TestRelay};
/// Test 5: Live sync Layer 2 events
///
/// Verifies that Layer 2 events (kind 1618 issues) published to one relay
/// are synced to another relay in real-time via discovery.
///
/// Flow:
/// 1. Start relay_a (source)
/// 2. Start relay_b (with sync enabled, no bootstrap)
/// 3. Send announcement to both relays (triggers discovery)
/// 4. Publish Layer 2 issue to relay_a
/// 5. Verify event syncs to relay_b within 5 seconds
#[tokio::test]
async fn test_live_sync_layer2_events() {
// 1. Start source relay (relay_a)
let relay_a = TestRelay::start().await;
println!(
"relay_a started at {} (domain: {})",
relay_a.url(),
relay_a.domain()
);
// 2. Start relay_b with sync enabled (no bootstrap - sync via discovery)
let relay_b = TestRelay::start_with_sync(None).await;
println!(
"relay_b started at {} (domain: {})",
relay_b.url(),
relay_b.domain()
);
// 3. Create test keys
let keys = Keys::generate();
// 4. Create a repository announcement that lists BOTH relays
let repo_id = "test-repo-live-l2";
let announcement =
create_repo_announcement(&keys, &[&relay_a.domain(), &relay_b.domain()], repo_id);
println!(
"Created announcement {} (kind {})",
announcement.id,
announcement.kind.as_u16()
);
// 5. Send announcement to relay_a
let client_a = TestClient::new(relay_a.url(), keys.clone())
.await
.expect("Failed to connect to relay_a");
client_a
.send_event(&announcement)
.await
.expect("Failed to send announcement to relay_a");
println!("Announcement sent to relay_a");
// 6. Send announcement to relay_b (triggers discovery of relay_a)
let client_b = TestClient::new(relay_b.url(), keys.clone())
.await
.expect("Failed to connect to relay_b");
client_b
.send_event(&announcement)
.await
.expect("Failed to send announcement to relay_b");
println!("Announcement sent to relay_b (triggers discovery)");
// 7. Wait for discovery to complete
tokio::time::sleep(Duration::from_secs(1)).await;
// 8. Create and send a Layer 2 issue event (using helper)
let repo_coordinate = repo_coord(&keys, repo_id);
let issue = build_layer2_issue_event(&keys, &repo_coordinate, "Test Issue for Live Sync")
.expect("Failed to create issue event");
let issue_id = issue.id;
println!("Created issue {} (kind {})", issue_id, issue.kind.as_u16());
for tag in issue.tags.iter() {
println!(" Tag: {:?}", tag.as_slice());
}
// Send issue to relay_a only
client_a
.send_event(&issue)
.await
.expect("Failed to send issue to relay_a");
println!("Issue sent to relay_a");
client_a.disconnect().await;
client_b.disconnect().await;
// 9. Wait and verify event syncs to relay_b
let filter = Filter::new()
.kind(Kind::Custom(KIND_ISSUE))
.author(keys.public_key())
.id(issue_id);
let synced = wait_for_event_on_relay(relay_b.url(), filter, Duration::from_secs(5)).await;
println!("Issue {} synced to relay_b: {}", issue_id, synced);
// 10. Cleanup
relay_b.stop().await;
relay_a.stop().await;
assert!(
synced,
"Layer 2 issue {} should have synced from relay_a to relay_b in real-time",
issue_id
);
}
/// Test 6: Live sync Layer 3 events
///
/// Verifies that Layer 3 events (comments) sync when they reference Layer 2 events.
///
/// Flow:
/// 1. Start relay_a and relay_b (with sync enabled)
/// 2. Send announcement to both relays (triggers discovery)
/// 3. Publish Layer 2 issue to relay_a
/// 4. Wait for Layer 2 issue to sync to relay_b
/// 5. Publish Layer 3 comment (referencing the issue) to relay_a
/// 6. Verify comment syncs to relay_b within 5 seconds
/// 7. Verify comment has correct 'E' tag reference
///
#[tokio::test]
async fn test_live_sync_layer3_events() {
// 1. Start relays
let relay_a = TestRelay::start().await;
println!(
"relay_a started at {} (domain: {})",
relay_a.url(),
relay_a.domain()
);
let relay_b = TestRelay::start_with_sync(None).await;
println!(
"relay_b started at {} (domain: {})",
relay_b.url(),
relay_b.domain()
);
let keys = Keys::generate();
// 2. Create and send repository announcement to both relays
let repo_id = "test-repo-live-l3";
let announcement =
create_repo_announcement(&keys, &[&relay_a.domain(), &relay_b.domain()], repo_id);
let client_a = TestClient::new(relay_a.url(), keys.clone())
.await
.expect("Failed to connect to relay_a");
let client_b = TestClient::new(relay_b.url(), keys.clone())
.await
.expect("Failed to connect to relay_b");
client_a
.send_event(&announcement)
.await
.expect("Failed to send announcement to relay_a");
println!("Announcement sent to relay_a");
client_b
.send_event(&announcement)
.await
.expect("Failed to send announcement to relay_b");
println!("Announcement sent to relay_b (triggers discovery)");
// 3. Wait for discovery
tokio::time::sleep(Duration::from_secs(1)).await;
// 4. Create and send Layer 2 issue
let repo_coordinate = repo_coord(&keys, repo_id);
let issue = build_layer2_issue_event(&keys, &repo_coordinate, "Parent Issue for Comment Test")
.expect("Failed to create issue");
let issue_id = issue.id;
client_a
.send_event(&issue)
.await
.expect("Failed to send issue");
println!("Layer 2 issue {} sent to relay_a", issue_id);
// 5. Create and send Layer 3 comment IMMEDIATELY (before waiting for sync)
// This tests that subscriptions without 'since' will catch pre-existing events
let comment = build_layer3_comment_with_uppercase_e_tag(
&keys,
&issue_id,
"This is a comment on the issue",
)
.expect("Failed to create comment");
let comment_id = comment.id;
println!(
"Created comment {} (kind {})",
comment_id,
comment.kind.as_u16()
);
for tag in comment.tags.iter() {
println!(" Tag: {:?}", tag.as_slice());
}
client_a
.send_event(&comment)
.await
.expect("Failed to send comment");
println!(
"Layer 3 comment {} sent to relay_a BEFORE Layer 3 subscription established",
comment_id
);
// 6. Now wait for issue to sync to relay_b (this triggers Layer 3 filter creation)
tokio::time::sleep(Duration::from_secs(2)).await;
let issue_filter = Filter::new().kind(Kind::Custom(KIND_ISSUE)).id(issue_id);
let issue_synced =
wait_for_event_on_relay(relay_b.url(), issue_filter, Duration::from_secs(3)).await;
println!("Issue synced to relay_b: {}", issue_synced);
client_a.disconnect().await;
client_b.disconnect().await;
// 7. Wait and verify comment syncs to relay_b
let comment_filter = Filter::new()
.kind(Kind::Custom(KIND_COMMENT))
.author(keys.public_key())
.id(comment_id);
let comment_synced =
wait_for_event_on_relay(relay_b.url(), comment_filter, Duration::from_secs(5)).await;
println!(
"Comment {} synced to relay_b: {}",
comment_id, comment_synced
);
// 8. Verify the comment has correct 'E' tag reference
let mut has_correct_ref = false;
if comment_synced {
let temp_keys = Keys::generate();
let client = Client::new(temp_keys);
if client.add_relay(relay_b.url()).await.is_ok() {
client.connect().await;
tokio::time::sleep(Duration::from_millis(500)).await;
let fetch_filter = Filter::new()
.kind(Kind::Custom(KIND_COMMENT))
.id(comment_id);
if let Ok(events) = client
.fetch_events(fetch_filter, Duration::from_secs(2))
.await
{
if let Some(event) = events.first() {
// Check for 'E' tag with parent event ID
for tag in event.tags.iter() {
let slice = tag.as_slice();
if slice.first() == Some(&"E".to_string())
&& slice.get(1) == Some(&issue_id.to_hex())
{
has_correct_ref = true;
println!("Found correct E tag reference to issue");
break;
}
}
}
}
client.disconnect().await;
}
}
// 9. Cleanup
relay_b.stop().await;
relay_a.stop().await;
assert!(
issue_synced,
"Layer 2 issue {} should have synced first",
issue_id
);
assert!(
comment_synced,
"Layer 3 comment {} should have synced to relay_b",
comment_id
);
assert!(
has_correct_ref,
"Comment should have 'E' tag referencing issue {}",
issue_id
);
}
/// Test 7: Live sync event ordering
///
/// Verifies that events arrive in chronological order when synced.
/// Note: We test ordering based on created_at timestamps, allowing for
/// minor timing variations inherent in async systems.
///
/// Flow:
/// 1. Start relay_a and relay_b (with sync enabled)
/// 2. Send announcement to both relays (triggers discovery)
/// 3. Publish 3 Layer 2 events to relay_a with 100ms delays between them
/// 4. Collect events from relay_b
/// 5. Verify events are ordered by created_at timestamp
#[tokio::test]
async fn test_live_sync_event_ordering() {
// 1. Start relays
let relay_a = TestRelay::start().await;
println!(
"relay_a started at {} (domain: {})",
relay_a.url(),
relay_a.domain()
);
let relay_b = TestRelay::start_with_sync(None).await;
println!(
"relay_b started at {} (domain: {})",
relay_b.url(),
relay_b.domain()
);
let keys = Keys::generate();
// 2. Create and send repository announcement to both relays
let repo_id = "test-repo-ordering";
let announcement =
create_repo_announcement(&keys, &[&relay_a.domain(), &relay_b.domain()], repo_id);
let client_a = TestClient::new(relay_a.url(), keys.clone())
.await
.expect("Failed to connect to relay_a");
let client_b = TestClient::new(relay_b.url(), keys.clone())
.await
.expect("Failed to connect to relay_b");
client_a
.send_event(&announcement)
.await
.expect("Failed to send announcement to relay_a");
client_b
.send_event(&announcement)
.await
.expect("Failed to send announcement to relay_b");
println!("Announcements sent to both relays");
// 3. Wait for discovery
tokio::time::sleep(Duration::from_secs(1)).await;
// 4. Create and send 3 issues with delays between them
let repo_coordinate = repo_coord(&keys, repo_id);
let mut issue_ids = Vec::new();
let mut expected_order_timestamps = Vec::new();
for i in 1..=3 {
let issue = build_layer2_issue_event(
&keys,
&repo_coordinate,
&format!("Ordering Test Issue {}", i),
)
.expect("Failed to create issue");
// Store the created_at timestamp for ordering verification
expected_order_timestamps.push(issue.created_at);
issue_ids.push(issue.id);
println!(
"Created issue {} at timestamp {}",
issue.id, issue.created_at
);
client_a
.send_event(&issue)
.await
.unwrap_or_else(|_| panic!("Failed to send issue {}", i));
// Delay between events to ensure different timestamps
tokio::time::sleep(Duration::from_millis(150)).await;
}
client_a.disconnect().await;
client_b.disconnect().await;
// 5. Wait for all events to sync
tokio::time::sleep(Duration::from_secs(3)).await;
// 6. Fetch all events from relay_b
let temp_keys = Keys::generate();
let client = Client::new(temp_keys);
let events_found: Vec<Event>;
if client.add_relay(relay_b.url()).await.is_ok() {
client.connect().await;
tokio::time::sleep(Duration::from_millis(500)).await;
let filter = Filter::new()
.kind(Kind::Custom(KIND_ISSUE))
.author(keys.public_key());
match client.fetch_events(filter, Duration::from_secs(3)).await {
Ok(events) => {
events_found = events.into_iter().collect();
}
Err(e) => {
println!("Failed to fetch events: {}", e);
events_found = Vec::new();
}
}
client.disconnect().await;
} else {
events_found = Vec::new();
}
// 7. Verify we got events
let found_count = events_found.len();
println!("Found {} events on relay_b", found_count);
// Filter to only our test events (by ID)
let test_events: Vec<&Event> = events_found
.iter()
.filter(|e| issue_ids.contains(&e.id))
.collect();
println!(
"Found {} test events (out of {} total)",
test_events.len(),
events_found.len()
);
// 8. Check ordering by created_at timestamp
let mut ordered_correctly = true;
if test_events.len() >= 2 {
// Sort by created_at and check order matches
let mut sorted_events = test_events.clone();
sorted_events.sort_by_key(|e| e.created_at);
for (i, event) in sorted_events.iter().enumerate() {
println!(
"Event {} sorted: {} at timestamp {}",
i + 1,
event.id,
event.created_at
);
}
// Verify ascending timestamp order
for window in sorted_events.windows(2) {
if window[0].created_at > window[1].created_at {
ordered_correctly = false;
println!(
"Order violation: {} ({}) > {} ({})",
window[0].id, window[0].created_at, window[1].id, window[1].created_at
);
}
}
}
// 9. Cleanup
relay_b.stop().await;
relay_a.stop().await;
// Assert based on what we found
// Note: We may not get all 3 events due to timing, but what we get should be ordered
assert!(
test_events.len() >= 2,
"Should have synced at least 2 of 3 events; found {}",
test_events.len()
);
assert!(
ordered_correctly,
"Events should be ordered by created_at timestamp"
);
}
|