-
-
Notifications
You must be signed in to change notification settings - Fork 160
Expand file tree
/
Copy pathoperations.rs
More file actions
3128 lines (2791 loc) · 118 KB
/
Copy pathoperations.rs
File metadata and controls
3128 lines (2791 loc) · 118 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
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use anyhow::{anyhow, bail};
use freenet::{
config::{ConfigArgs, InlineGwConfig, NetworkArgs, SecretArgs, WebsocketApiArgs},
dev_tool::TransportKeypair,
local_node::NodeConfig,
server::serve_gateway,
test_utils::{
self, load_delegate, make_get, make_put, make_subscribe, make_update,
verify_contract_exists, with_peer_id, TestLogger,
},
};
use freenet_stdlib::{
client_api::{ClientRequest, ContractResponse, HostResponse, QueryResponse, WebApi},
prelude::*,
};
use futures::FutureExt;
use rand::{random, Rng, SeedableRng};
use serde::Deserialize;
use std::{
net::{Ipv4Addr, TcpListener},
path::Path,
sync::{LazyLock, Mutex},
time::Duration,
};
use testresult::TestResult;
use tokio::select;
use tokio::time::timeout;
use tokio_tungstenite::connect_async;
use tracing::{span, Instrument, Level};
static RNG: LazyLock<Mutex<rand::rngs::StdRng>> = LazyLock::new(|| {
Mutex::new(rand::rngs::StdRng::from_seed(
*b"0102030405060708090a0b0c0d0e0f10",
))
});
struct PresetConfig {
temp_dir: tempfile::TempDir,
}
async fn base_node_test_config(
is_gateway: bool,
gateways: Vec<String>,
public_port: Option<u16>,
ws_api_port: u16,
) -> anyhow::Result<(ConfigArgs, PresetConfig)> {
const _DEFAULT_RATE_LIMIT: usize = 1024 * 1024 * 10; // 10 MB/s
if is_gateway {
assert!(public_port.is_some());
}
let temp_dir = tempfile::tempdir()?;
let key = TransportKeypair::new();
let transport_keypair = temp_dir.path().join("private.pem");
key.save(&transport_keypair)?;
key.public().save(temp_dir.path().join("public.pem"))?;
let config = ConfigArgs {
ws_api: WebsocketApiArgs {
address: Some(Ipv4Addr::LOCALHOST.into()),
ws_api_port: Some(ws_api_port),
token_ttl_seconds: None,
token_cleanup_interval_seconds: None,
},
network_api: NetworkArgs {
public_address: Some(Ipv4Addr::LOCALHOST.into()),
public_port,
is_gateway,
skip_load_from_network: true,
gateways: Some(gateways),
location: Some(RNG.lock().unwrap().random()),
ignore_protocol_checking: true,
address: Some(Ipv4Addr::LOCALHOST.into()),
network_port: public_port,
bandwidth_limit: None,
blocked_addresses: None,
},
config_paths: {
freenet::config::ConfigPathsArgs {
config_dir: Some(temp_dir.path().to_path_buf()),
data_dir: Some(temp_dir.path().to_path_buf()),
}
},
secrets: SecretArgs {
transport_keypair: Some(transport_keypair),
..Default::default()
},
..Default::default()
};
Ok((config, PresetConfig { temp_dir }))
}
fn gw_config(port: u16, path: &Path) -> anyhow::Result<InlineGwConfig> {
Ok(InlineGwConfig {
address: (Ipv4Addr::LOCALHOST, port).into(),
location: Some(random()),
public_key_path: path.join("public.pem"),
})
}
async fn get_contract(
client: &mut WebApi,
key: ContractKey,
temp_dir: &tempfile::TempDir,
) -> anyhow::Result<(ContractContainer, WrappedState)> {
make_get(client, key, true, false).await?;
loop {
let resp = tokio::time::timeout(Duration::from_secs(30), client.recv()).await;
match resp {
Ok(Ok(HostResponse::ContractResponse(ContractResponse::GetResponse {
key,
contract: Some(contract),
state,
}))) => {
verify_contract_exists(temp_dir.path(), key).await?;
return Ok((contract, state));
}
Ok(Ok(other)) => {
tracing::warn!("unexpected response while waiting for get: {:?}", other);
}
Ok(Err(e)) => {
bail!("Error receiving get response: {}", e);
}
Err(_) => {
bail!("Timeout waiting for get response");
}
}
}
}
/// Test PUT operation across two peers (gateway and peer)
#[test_log::test(tokio::test(flavor = "multi_thread", worker_threads = 4))]
async fn test_put_contract() -> TestResult {
const TEST_CONTRACT: &str = "test-contract-integration";
let contract = test_utils::load_contract(TEST_CONTRACT, vec![].into())?;
let contract_key = contract.key();
let initial_state = test_utils::create_empty_todo_list();
let wrapped_state = WrappedState::from(initial_state);
let network_socket_b = TcpListener::bind("127.0.0.1:0")?;
let ws_api_port_socket_a = TcpListener::bind("127.0.0.1:0")?;
let ws_api_port_socket_b = TcpListener::bind("127.0.0.1:0")?;
let (config_b, preset_cfg_b, config_b_gw) = {
let (cfg, preset) = base_node_test_config(
true,
vec![],
Some(network_socket_b.local_addr()?.port()),
ws_api_port_socket_b.local_addr()?.port(),
)
.await?;
let public_port = cfg.network_api.public_port.unwrap();
let path = preset.temp_dir.path().to_path_buf();
(cfg, preset, gw_config(public_port, &path)?)
};
let ws_api_port_peer_b = config_b.ws_api.ws_api_port.unwrap();
let (config_a, preset_cfg_a) = base_node_test_config(
false,
vec![serde_json::to_string(&config_b_gw)?],
None,
ws_api_port_socket_a.local_addr()?.port(),
)
.await?;
let ws_api_port_peer_a = config_a.ws_api.ws_api_port.unwrap();
tracing::info!("Node A data dir: {:?}", preset_cfg_b.temp_dir.path());
tracing::info!("Node B data dir: {:?}", preset_cfg_a.temp_dir.path());
std::mem::drop(ws_api_port_socket_a); // Free the port so it does not fail on initialization
let node_a = async move {
let _span = with_peer_id("peer-a");
tracing::info!("Starting peer A node");
let config = config_a.build().await?;
let node = NodeConfig::new(config.clone())
.await?
.build(serve_gateway(config.ws_api).await)
.await?;
tracing::info!("Peer A node running");
node.run().await
}
.boxed_local();
std::mem::drop(network_socket_b); // Free the port so it does not fail on initialization
std::mem::drop(ws_api_port_socket_b);
let node_b = async {
let _span = with_peer_id("gateway");
tracing::info!("Starting gateway node");
let config = config_b.build().await?;
let node = NodeConfig::new(config.clone())
.await?
.build(serve_gateway(config.ws_api).await)
.await?;
tracing::info!("Gateway node running");
node.run().await
}
.boxed_local();
let test = tokio::time::timeout(Duration::from_secs(180), async {
// Wait for nodes to start up
tracing::info!("Waiting for nodes to start up...");
tokio::time::sleep(Duration::from_secs(15)).await;
tracing::info!("Nodes should be ready, proceeding with test...");
// Connect to node A's websocket API
let uri = format!(
"ws://127.0.0.1:{ws_api_port_peer_a}/v1/contract/command?encodingProtocol=native"
);
let (stream, _) = connect_async(&uri).await?;
let mut client_api_a = WebApi::start(stream);
make_put(
&mut client_api_a,
wrapped_state.clone(),
contract.clone(),
false,
)
.await?;
// Wait for put response (increased timeout for CI environments)
tracing::info!("Waiting for PUT response...");
let resp = tokio::time::timeout(Duration::from_secs(120), client_api_a.recv()).await;
match resp {
Ok(Ok(HostResponse::ContractResponse(ContractResponse::PutResponse { key }))) => {
tracing::info!("PUT successful for contract: {}", key);
assert_eq!(key, contract_key);
}
Ok(Ok(other)) => {
tracing::warn!("unexpected response while waiting for put: {:?}", other);
}
Ok(Err(e)) => {
bail!("Error receiving put response: {}", e);
}
Err(_) => {
bail!("Timeout waiting for put response after 120 seconds");
}
}
{
// Wait for get response from node A
tracing::info!("getting contract from A");
let (response_contract, response_state) =
get_contract(&mut client_api_a, contract_key, &preset_cfg_b.temp_dir).await?;
let response_key = response_contract.key();
// Verify the responses
assert_eq!(response_key, contract_key);
assert_eq!(response_contract, contract);
assert_eq!(response_state, wrapped_state);
}
{
// Connect to node B's websocket API
let uri = format!(
"ws://127.0.0.1:{ws_api_port_peer_b}/v1/contract/command?encodingProtocol=native"
);
let (stream, _) = connect_async(&uri).await?;
let mut client_api_b = WebApi::start(stream);
// Wait for get response from node B
let (response_contract, response_state) =
get_contract(&mut client_api_b, contract_key, &preset_cfg_b.temp_dir).await?;
let response_key = response_contract.key();
// Verify the responses
assert_eq!(response_key, contract_key);
assert_eq!(response_contract, contract);
assert_eq!(response_state, wrapped_state);
// Properly close the client
client_api_b
.send(ClientRequest::Disconnect { cause: None })
.await?;
tokio::time::sleep(Duration::from_millis(100)).await;
}
// Close the first client as well
client_api_a
.send(ClientRequest::Disconnect { cause: None })
.await?;
tokio::time::sleep(Duration::from_millis(100)).await;
Ok::<_, anyhow::Error>(())
});
select! {
a = node_a => {
let Err(a) = a;
return Err(anyhow!(a).into());
}
b = node_b => {
let Err(b) = b;
return Err(anyhow!(b).into());
}
r = test => {
r??;
// Give time for cleanup before dropping nodes
tokio::time::sleep(Duration::from_secs(3)).await;
}
}
Ok(())
}
#[test_log::test(tokio::test(flavor = "multi_thread", worker_threads = 4))]
async fn test_update_contract() -> TestResult {
// Load test contract
const TEST_CONTRACT: &str = "test-contract-integration";
let contract = test_utils::load_contract(TEST_CONTRACT, vec![].into())?;
let contract_key = contract.key();
// Create initial state with empty todo list
let initial_state = test_utils::create_empty_todo_list();
let wrapped_state = WrappedState::from(initial_state);
// Create network sockets
let network_socket_b = TcpListener::bind("127.0.0.1:0")?;
let ws_api_port_socket_a = TcpListener::bind("127.0.0.1:0")?;
let ws_api_port_socket_b = TcpListener::bind("127.0.0.1:0")?;
// Configure gateway node B
let (config_b, preset_cfg_b, config_b_gw) = {
let (cfg, preset) = base_node_test_config(
true,
vec![],
Some(network_socket_b.local_addr()?.port()),
ws_api_port_socket_b.local_addr()?.port(),
)
.await?;
let public_port = cfg.network_api.public_port.unwrap();
let path = preset.temp_dir.path().to_path_buf();
(cfg, preset, gw_config(public_port, &path)?)
};
// Configure client node A
let (config_a, preset_cfg_a) = base_node_test_config(
false,
vec![serde_json::to_string(&config_b_gw)?],
None,
ws_api_port_socket_a.local_addr()?.port(),
)
.await?;
let ws_api_port = config_a.ws_api.ws_api_port.unwrap();
// Log data directories for debugging
tracing::info!("Node A data dir: {:?}", preset_cfg_a.temp_dir.path());
tracing::info!("Node B (gw) data dir: {:?}", preset_cfg_b.temp_dir.path());
// Start node A (client)
std::mem::drop(ws_api_port_socket_a); // Free the port so it does not fail on initialization
let node_a = async move {
let config = config_a.build().await?;
let node = NodeConfig::new(config.clone())
.await?
.build(serve_gateway(config.ws_api).await)
.await?;
node.run().await
}
.boxed_local();
// Start node B (gateway)
std::mem::drop(network_socket_b); // Free the port so it does not fail on initialization
std::mem::drop(ws_api_port_socket_b);
let node_b = async {
let config = config_b.build().await?;
let node = NodeConfig::new(config.clone())
.await?
.build(serve_gateway(config.ws_api).await)
.await?;
node.run().await
}
.boxed_local();
let test = tokio::time::timeout(Duration::from_secs(180), async {
// Wait for nodes to start up
tokio::time::sleep(Duration::from_secs(20)).await; // Increased sleep duration
// Connect to node A websocket API
let uri =
format!("ws://127.0.0.1:{ws_api_port}/v1/contract/command?encodingProtocol=native");
let (stream, _) = connect_async(&uri).await?;
let mut client_api_a = WebApi::start(stream);
// Put contract with initial state
make_put(
&mut client_api_a,
wrapped_state.clone(),
contract.clone(),
false,
)
.await?;
// Wait for put response (increased timeout for CI environments)
tracing::info!("Waiting for PUT response...");
let resp = tokio::time::timeout(Duration::from_secs(120), client_api_a.recv()).await;
match resp {
Ok(Ok(HostResponse::ContractResponse(ContractResponse::PutResponse { key }))) => {
tracing::info!("PUT successful for contract: {}", key);
assert_eq!(key, contract_key, "Contract key mismatch in PUT response");
}
Ok(Ok(other)) => {
tracing::warn!("unexpected response while waiting for put: {:?}", other);
}
Ok(Err(e)) => {
bail!("Error receiving put response: {}", e);
}
Err(_) => {
bail!("Timeout waiting for put response after 120 seconds");
}
}
// Create a new to-do list by deserializing the current state, adding a task, and serializing it back
let mut todo_list: test_utils::TodoList = serde_json::from_slice(wrapped_state.as_ref())
.unwrap_or_else(|_| test_utils::TodoList {
tasks: Vec::new(),
version: 0,
});
// Add a task directly to the list
todo_list.tasks.push(test_utils::Task {
id: 1,
title: "Implement contract".to_string(),
description: "Create a smart contract for the todo list".to_string(),
completed: false,
priority: 3,
});
// Serialize the updated list back to bytes
let updated_bytes = serde_json::to_vec(&todo_list).unwrap();
let updated_state = WrappedState::from(updated_bytes);
let expected_version_after_update = todo_list.version + 1;
make_update(&mut client_api_a, contract_key, updated_state.clone()).await?;
// Wait for update response
let resp = tokio::time::timeout(Duration::from_secs(30), client_api_a.recv()).await;
match resp {
Ok(Ok(HostResponse::ContractResponse(ContractResponse::UpdateResponse {
key,
summary: _,
}))) => {
assert_eq!(
key, contract_key,
"Contract key mismatch in UPDATE response"
);
}
Ok(Ok(other)) => {
bail!("unexpected response while waiting for update: {:?}", other);
}
Ok(Err(e)) => {
bail!("Client A: Error receiving update response: {}", e);
}
Err(_) => {
bail!("Client A: Timeout waiting for update response");
}
}
// Verify the updated state with GET
{
// Wait for get response from node A
let (response_contract, response_state) =
get_contract(&mut client_api_a, contract_key, &preset_cfg_b.temp_dir).await?;
assert_eq!(
response_contract.key(),
contract_key,
"Contract key mismatch in GET response"
);
assert_eq!(
response_contract, contract,
"Contract content mismatch in GET response"
);
// Compare the deserialized updated content
let response_todo_list: test_utils::TodoList =
serde_json::from_slice(response_state.as_ref())
.expect("Failed to deserialize response state");
let expected_todo_list: test_utils::TodoList =
serde_json::from_slice(updated_state.as_ref())
.expect("Failed to deserialize expected state");
assert_eq!(
response_todo_list.version, expected_version_after_update,
"Version should match"
);
assert_eq!(
response_todo_list.tasks.len(),
expected_todo_list.tasks.len(),
"Number of tasks should match"
);
// Verify that the task exists and has the correct values
assert_eq!(response_todo_list.tasks.len(), 1, "Should have one task");
assert_eq!(response_todo_list.tasks[0].id, 1, "Task ID should be 1");
assert_eq!(
response_todo_list.tasks[0].title, "Implement contract",
"Task title should match"
);
tracing::info!(
"Successfully verified updated state for contract {}",
contract_key
);
// Print states for debugging
tracing::debug!(
"Response state: {:?}, Expected state: {:?}",
response_todo_list,
expected_todo_list
);
}
Ok::<_, anyhow::Error>(())
});
// Wait for test completion or node failures
select! {
a = node_a => {
let Err(a) = a;
return Err(anyhow!("Node A failed: {}", a).into());
}
b = node_b => {
let Err(b) = b;
return Err(anyhow!("Node B failed: {}", b).into());
}
r = test => {
r??;
// Keep nodes alive for pending operations to complete
tokio::time::sleep(Duration::from_secs(3)).await;
}
}
Ok(())
}
/// Test that a second PUT to an already cached contract persists the merged state.
/// This is a regression test for issue #1995.
#[test_log::test(tokio::test(flavor = "multi_thread", worker_threads = 4))]
async fn test_put_merge_persists_state() -> TestResult {
// Load test contract
const TEST_CONTRACT: &str = "test-contract-integration";
let contract = test_utils::load_contract(TEST_CONTRACT, vec![].into())?;
let contract_key = contract.key();
// Create initial state with empty todo list
let initial_state = test_utils::create_empty_todo_list();
let initial_wrapped_state = WrappedState::from(initial_state);
// Create network sockets
let network_socket_b = TcpListener::bind("127.0.0.1:0")?;
let ws_api_port_socket_a = TcpListener::bind("127.0.0.1:0")?;
let ws_api_port_socket_b = TcpListener::bind("127.0.0.1:0")?;
// Configure gateway node B
let (config_b, preset_cfg_b, config_b_gw) = {
let (cfg, preset) = base_node_test_config(
true,
vec![],
Some(network_socket_b.local_addr()?.port()),
ws_api_port_socket_b.local_addr()?.port(),
)
.await?;
let public_port = cfg.network_api.public_port.unwrap();
let path = preset.temp_dir.path().to_path_buf();
(cfg, preset, gw_config(public_port, &path)?)
};
let ws_api_port_peer_b = config_b.ws_api.ws_api_port.unwrap();
// Configure peer node A
let (config_a, preset_cfg_a) = base_node_test_config(
false,
vec![serde_json::to_string(&config_b_gw)?],
None,
ws_api_port_socket_a.local_addr()?.port(),
)
.await?;
let ws_api_port_peer_a = config_a.ws_api.ws_api_port.unwrap();
tracing::info!("Node A data dir: {:?}", preset_cfg_a.temp_dir.path());
tracing::info!("Node B (gw) data dir: {:?}", preset_cfg_b.temp_dir.path());
// Start node A (peer)
std::mem::drop(ws_api_port_socket_a);
let node_a = async move {
let _span = with_peer_id("peer-a");
tracing::info!("Starting peer A node");
let config = config_a.build().await?;
let node = NodeConfig::new(config.clone())
.await?
.build(serve_gateway(config.ws_api).await)
.await?;
tracing::info!("Peer A node running");
node.run().await
}
.boxed_local();
// Start node B (gateway)
std::mem::drop(network_socket_b);
std::mem::drop(ws_api_port_socket_b);
let node_b = async {
let _span = with_peer_id("gateway");
tracing::info!("Starting gateway node");
let config = config_b.build().await?;
let node = NodeConfig::new(config.clone())
.await?
.build(serve_gateway(config.ws_api).await)
.await?;
tracing::info!("Gateway node running");
node.run().await
}
.boxed_local();
let test = tokio::time::timeout(Duration::from_secs(180), async {
// Wait for nodes to start up
tracing::info!("Waiting for nodes to start up...");
tokio::time::sleep(Duration::from_secs(15)).await;
tracing::info!("Nodes should be ready, proceeding with test...");
// Connect to node A's websocket API
let uri = format!(
"ws://127.0.0.1:{ws_api_port_peer_a}/v1/contract/command?encodingProtocol=native"
);
let (stream, _) = connect_async(&uri).await?;
let mut client_api_a = WebApi::start(stream);
// First PUT: Store initial contract state
tracing::info!("Sending first PUT with initial state...");
make_put(
&mut client_api_a,
initial_wrapped_state.clone(),
contract.clone(),
false,
)
.await?;
// Wait for first put response
let resp = tokio::time::timeout(Duration::from_secs(120), client_api_a.recv()).await;
match resp {
Ok(Ok(HostResponse::ContractResponse(ContractResponse::PutResponse { key }))) => {
tracing::info!("First PUT successful for contract: {}", key);
assert_eq!(key, contract_key);
}
Ok(Ok(other)) => {
bail!("Unexpected response for first PUT: {:?}", other);
}
Ok(Err(e)) => {
bail!("Error receiving first PUT response: {}", e);
}
Err(_) => {
bail!("Timeout waiting for first PUT response");
}
}
// Wait a bit to ensure state is fully cached
tokio::time::sleep(Duration::from_secs(2)).await;
// Create updated state with more data (simulating a state merge)
let mut updated_todo_list: test_utils::TodoList =
serde_json::from_slice(initial_wrapped_state.as_ref()).unwrap();
// Add multiple tasks to make the state larger
for i in 1..=5 {
updated_todo_list.tasks.push(test_utils::Task {
id: i,
title: format!("Task {}", i),
description: format!("Description for task {}", i),
completed: false,
priority: i as u8,
});
}
let updated_bytes = serde_json::to_vec(&updated_todo_list).unwrap();
let updated_wrapped_state = WrappedState::from(updated_bytes);
tracing::info!(
"Initial state size: {} bytes, Updated state size: {} bytes",
initial_wrapped_state.as_ref().len(),
updated_wrapped_state.as_ref().len()
);
// Second PUT: Update the already-cached contract with new state
// This tests the bug fix - the merged state should be persisted
tracing::info!("Sending second PUT with updated state...");
make_put(
&mut client_api_a,
updated_wrapped_state.clone(),
contract.clone(),
false,
)
.await?;
// Wait for second put response
let resp = tokio::time::timeout(Duration::from_secs(120), client_api_a.recv()).await;
match resp {
Ok(Ok(HostResponse::ContractResponse(ContractResponse::PutResponse { key }))) => {
tracing::info!("Second PUT successful for contract: {}", key);
assert_eq!(key, contract_key);
}
Ok(Ok(other)) => {
bail!("Unexpected response for second PUT: {:?}", other);
}
Ok(Err(e)) => {
bail!("Error receiving second PUT response: {}", e);
}
Err(_) => {
bail!("Timeout waiting for second PUT response");
}
}
// Wait a bit to ensure the merge and persistence completes
tokio::time::sleep(Duration::from_secs(2)).await;
// The key test: GET from gateway to verify it persisted the merged state
// This is the bug from issue #1995 - gateway receives PUT for already-cached
// contract, merges state, but doesn't persist it
let uri = format!(
"ws://127.0.0.1:{ws_api_port_peer_b}/v1/contract/command?encodingProtocol=native"
);
let (stream, _) = connect_async(&uri).await?;
let mut client_api_gateway = WebApi::start(stream);
tracing::info!("Getting contract from gateway to verify merged state was persisted...");
let (response_contract_gw, response_state_gw) = get_contract(
&mut client_api_gateway,
contract_key,
&preset_cfg_b.temp_dir,
)
.await?;
assert_eq!(response_contract_gw.key(), contract_key);
let response_todo_list_gw: test_utils::TodoList =
serde_json::from_slice(response_state_gw.as_ref())
.expect("Failed to deserialize state from gateway");
tracing::info!(
"Gateway returned state with {} tasks, size {} bytes",
response_todo_list_gw.tasks.len(),
response_state_gw.as_ref().len()
);
// This is the key assertion for issue #1995:
// Gateway received a PUT for an already-cached contract, merged the states,
// and should have PERSISTED the merged state (not just computed it)
assert_eq!(
response_todo_list_gw.tasks.len(),
5,
"Gateway should return merged state with 5 tasks (issue #1995: merged state must be persisted)"
);
// Verify the state size matches as additional confirmation
assert_eq!(
response_state_gw.as_ref().len(),
updated_wrapped_state.as_ref().len(),
"Gateway state size should match the updated state"
);
tracing::info!(
"✓ Test passed: Gateway correctly persisted merged state after second PUT (issue #1995 fixed)"
);
// Cleanup
client_api_a
.send(ClientRequest::Disconnect { cause: None })
.await?;
client_api_gateway
.send(ClientRequest::Disconnect { cause: None })
.await?;
tokio::time::sleep(Duration::from_millis(100)).await;
Ok::<_, anyhow::Error>(())
});
select! {
a = node_a => {
let Err(a) = a;
return Err(anyhow!(a).into());
}
b = node_b => {
let Err(b) = b;
return Err(anyhow!(b).into());
}
r = test => {
r??;
tokio::time::sleep(Duration::from_secs(3)).await;
}
}
Ok(())
}
// This test is disabled due to race conditions in subscription propagation logic.
// The test expects multiple clients across different nodes to receive subscription updates,
// but the PUT caching refactor (commits 2cd337b5-0d432347) changed the subscription semantics.
// Re-enabled after recent fixes to subscription logic - previously exhibited race conditions.
// If this test becomes flaky again, see issue #1798 for historical context.
#[test_log::test(tokio::test(flavor = "multi_thread", worker_threads = 4))]
async fn test_multiple_clients_subscription() -> TestResult {
// Initialize test logger with JSON format for better debugging
let _logger = TestLogger::new()
.with_json()
.with_level("freenet::operations::connect=debug,freenet::node::network_bridge::p2p_protoc=info,info")
.init();
// Load test contract
const TEST_CONTRACT: &str = "test-contract-integration";
let contract = test_utils::load_contract(TEST_CONTRACT, vec![].into())?;
let contract_key = contract.key();
// Create initial state with empty todo list
let initial_state = test_utils::create_empty_todo_list();
let wrapped_state = WrappedState::from(initial_state);
// Create network sockets
let network_socket_b = TcpListener::bind("127.0.0.1:0")?;
let ws_api_port_socket_a = TcpListener::bind("127.0.0.1:0")?;
let ws_api_port_socket_b = TcpListener::bind("127.0.0.1:0")?;
let ws_api_port_socket_c = TcpListener::bind("127.0.0.1:0")?; // Socket for node C (second client)
// Configure gateway node
let (config_gw, preset_cfg_b, gw_cfg) = {
let (cfg, preset) = base_node_test_config(
true,
vec![],
Some(network_socket_b.local_addr()?.port()),
ws_api_port_socket_b.local_addr()?.port(),
)
.await?;
let public_port = cfg.network_api.public_port.unwrap();
let path = preset.temp_dir.path().to_path_buf();
(cfg, preset, gw_config(public_port, &path)?)
};
// Configure client node A
let (config_a, preset_cfg_a) = base_node_test_config(
false,
vec![serde_json::to_string(&gw_cfg)?],
None,
ws_api_port_socket_a.local_addr()?.port(),
)
.await?;
let ws_api_port_a = config_a.ws_api.ws_api_port.unwrap();
// Configure client node B (second client node)
let (config_b, preset_cfg_c) = base_node_test_config(
false,
vec![serde_json::to_string(&gw_cfg)?],
None,
ws_api_port_socket_c.local_addr()?.port(),
)
.await?;
let ws_api_port_b = config_b.ws_api.ws_api_port.unwrap();
// Log data directories for debugging
tracing::info!("Node A data dir: {:?}", preset_cfg_a.temp_dir.path());
tracing::info!("Node B (gw) data dir: {:?}", preset_cfg_b.temp_dir.path());
tracing::info!("Node C data dir: {:?}", preset_cfg_c.temp_dir.path());
// Free ports so they don't fail on initialization
std::mem::drop(ws_api_port_socket_a);
std::mem::drop(network_socket_b);
std::mem::drop(ws_api_port_socket_b);
std::mem::drop(ws_api_port_socket_c);
// Start node A (first client)
let node_a = async move {
let _span = with_peer_id("node-a");
tracing::info!("Starting node A");
let config = config_a.build().await?;
let node = NodeConfig::new(config.clone())
.await?
.build(serve_gateway(config.ws_api).await)
.await?;
tracing::info!("Node A running");
node.run().await
}
.boxed_local();
// Start GW node
let node_gw = async {
let _span = with_peer_id("gateway");
tracing::info!("Starting gateway node");
let config = config_gw.build().await?;
let node = NodeConfig::new(config.clone())
.await?
.build(serve_gateway(config.ws_api).await)
.await?;
tracing::info!("Gateway node running");
node.run().await
}
.boxed_local();
// Start node B (second client)
let node_b = async {
let _span = with_peer_id("node-b");
tracing::info!("Starting node B");
let config = config_b.build().await?;
let node = NodeConfig::new(config.clone())
.await?
.build(serve_gateway(config.ws_api).await)
.await?;
tracing::info!("Node B running");
node.run().await
}
.boxed_local();
let test = tokio::time::timeout(Duration::from_secs(600), async {
// Wait for nodes to start up - CI environments need more time
tokio::time::sleep(Duration::from_secs(40)).await;
// Connect first client to node A's websocket API
tracing::info!("Starting WebSocket connections after 40s startup wait");
let start_time = std::time::Instant::now();
let uri_a =
format!("ws://127.0.0.1:{ws_api_port_a}/v1/contract/command?encodingProtocol=native");
let (stream1, _) = connect_async(&uri_a).await?;
let mut client_api1_node_a = WebApi::start(stream1);
// Connect second client to node A's websocket API
let (stream2, _) = connect_async(&uri_a).await?;
let mut client_api2_node_a = WebApi::start(stream2);
// Connect third client to node C's websocket API (different node)
let uri_c =
format!("ws://127.0.0.1:{ws_api_port_b}/v1/contract/command?encodingProtocol=native");
let (stream3, _) = connect_async(&uri_c).await?;
let mut client_api_node_b = WebApi::start(stream3);
// First client puts contract with initial state (without subscribing)
tracing::info!(
"Client 1: Starting PUT operation (elapsed: {:?})",
start_time.elapsed()
);
make_put(
&mut client_api1_node_a,
wrapped_state.clone(),
contract.clone(),
false, // subscribe=false - no automatic subscription
)
.await?;
// Wait for put response
loop {
let resp =
tokio::time::timeout(Duration::from_secs(120), client_api1_node_a.recv()).await;
match resp {
Ok(Ok(HostResponse::ContractResponse(ContractResponse::PutResponse { key }))) => {
assert_eq!(key, contract_key, "Contract key mismatch in PUT response");
tracing::info!(
"Client 1: PUT completed successfully (elapsed: {:?})",
start_time.elapsed()
);
break;
}
Ok(Ok(other)) => {
tracing::warn!("unexpected response while waiting for put: {:?}", other);
}
Ok(Err(e)) => {
bail!("Error receiving put response: {}", e);
}
Err(_) => {
bail!("Timeout waiting for put response");
}
}
}
// Explicitly subscribe client 1 to the contract using make_subscribe
make_subscribe(&mut client_api1_node_a, contract_key).await?;
// Wait for subscribe response
loop {
let resp =
tokio::time::timeout(Duration::from_secs(30), client_api1_node_a.recv()).await;
match resp {
Ok(Ok(HostResponse::ContractResponse(ContractResponse::SubscribeResponse {
key,
subscribed,
}))) => {
assert_eq!(
key, contract_key,
"Contract key mismatch in SUBSCRIBE response"
);
assert!(subscribed, "Failed to subscribe to contract");
tracing::info!("Client 1: Successfully subscribed to contract {}", key);
break;
}
Ok(Ok(other)) => {
tracing::warn!(
"Client 1: unexpected response while waiting for subscribe: {:?}",
other
);
}
Ok(Err(e)) => {
bail!("Client 1: Error receiving subscribe response: {}", e);
}
Err(_) => {