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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
//! Handling of contracts and delegates, including storage, execution, caching, etc.
//!
//! Internally uses the wasm_runtime module to execute contract and/or delegate instructions.
use std::sync::Arc;
use either::Either;
use freenet_stdlib::prelude::*;
mod executor;
mod fair_queue;
mod handler;
pub mod storages;
pub(crate) mod user_input;
pub(crate) use executor::{
Callback, ContractExecutor, ExecutorToEventLoopChannel, MAX_CREATED_DELEGATES_PER_NODE,
MAX_DELEGATE_CREATION_DEPTH, MAX_DELEGATE_CREATIONS_PER_CALL, NetworkEventListenerHalve,
SUBSCRIBER_NOTIFICATION_CHANNEL_SIZE, UpsertResult, mediator_channels,
mock_runtime::MockRuntime, op_request_channel, run_op_request_mediator,
};
// Re-export CRDT emulation functions for testing
pub use executor::mock_runtime::{clear_crdt_contracts, is_crdt_contract, register_crdt_contract};
pub(crate) use handler::{
ClientResponsesReceiver, ClientResponsesSender, ContractHandler, ContractHandlerChannel,
ContractHandlerEvent, NetworkContractHandler, SenderHalve, SessionMessage, StoreResponse,
WaitingResolution, WaitingTransaction, client_responses_channel, contract_handler_channel,
in_memory::{
MemoryContractHandler, MockWasmContractHandler, MockWasmHandlerBuilder,
SimulationContractHandler, SimulationHandlerBuilder,
},
};
pub use executor::{Executor, ExecutorError, OperationMode};
pub use handler::reset_event_id_counter;
use freenet_stdlib::client_api::DelegateRequest;
use tracing::Instrument;
use self::executor::DelegateNotificationReceiver;
use self::user_input::{CallerIdentity, UserInputPrompter};
/// Maximum iterations when handling contract requests to prevent infinite loops
const MAX_CONTRACT_REQUEST_ITERATIONS: usize = 100;
/// Maximum delegate notifications to drain per iteration.
/// Matches the same bounded-drain pattern as MAX_DRAIN_BATCH for contract events,
/// preventing delegate notification channel growth under sustained contract load.
const MAX_DELEGATE_DRAIN_BATCH: usize = 16;
/// Handle a delegate request, including any contract request messages in the response.
///
/// When a delegate emits contract request messages, this function:
/// 1. For GET: Fetches the contract state and sends GetContractResponse back
/// 2. For PUT: Upserts the contract state via `upsert_contract_state` (which automatically
/// propagates to the network via `BroadcastStateChange`), sends PutContractResponse back
/// 3. For UPDATE: Applies a state update via `upsert_contract_state` (same propagation),
/// sends UpdateContractResponse back
/// 4. For SUBSCRIBE: Registers in subscription registry, sends SubscribeContractResponse back
/// 5. Repeats until no more contract request messages
///
/// Returns the final response with contract request messages filtered out.
async fn handle_delegate_with_contract_requests<CH, P>(
contract_handler: &mut CH,
initial_req: DelegateRequest<'static>,
origin_contract: Option<&ContractInstanceId>,
delegate_key: &DelegateKey,
prompter: &P,
) -> Vec<OutboundDelegateMsg>
where
CH: ContractHandler + Send + 'static,
P: UserInputPrompter,
{
// Extract initial params from the request (only ApplicationMessages has params we need)
let initial_params = match &initial_req {
DelegateRequest::ApplicationMessages { params, .. } => params.clone(),
DelegateRequest::RegisterDelegate { .. } | DelegateRequest::UnregisterDelegate(_) | _ => {
Parameters::from(Vec::new())
}
};
let mut current_req = initial_req;
let current_params = initial_params;
let mut iterations = 0;
// Accumulate non-contract-request messages across iterations
let mut accumulated_messages: Vec<OutboundDelegateMsg> = Vec::new();
loop {
iterations += 1;
if iterations > MAX_CONTRACT_REQUEST_ITERATIONS {
tracing::error!(
delegate_key = %delegate_key,
iterations = iterations,
"Exceeded maximum contract request iterations, possible infinite loop"
);
// Return whatever we accumulated so far
return accumulated_messages;
}
// Execute the delegate request
let values = match contract_handler
.executor()
.execute_delegate_request(current_req, origin_contract, None)
.await
{
Ok(freenet_stdlib::client_api::HostResponse::DelegateResponse { key: _, values }) => {
values
}
Ok(freenet_stdlib::client_api::HostResponse::Ok) => Vec::new(),
Ok(_other) => {
tracing::error!(
delegate_key = %delegate_key,
phase = "unexpected_response",
"Unexpected response type from delegate request"
);
// Return whatever we accumulated so far
return accumulated_messages;
}
Err(err) => {
// Downgrade "not found" to warn — expected during legacy
// migration probes when old delegate WASM isn't on this node
if err.is_missing_delegate() {
tracing::warn!(
delegate_key = %delegate_key,
"Delegate not found in store (expected for migration probes)"
);
} else {
tracing::error!(
delegate_key = %delegate_key,
error = %err,
phase = "execution_failed",
"Failed executing delegate request"
);
}
// Return whatever we accumulated so far
return accumulated_messages;
}
};
// Check for contract request messages (GET, PUT, UPDATE, SUBSCRIBE), delegate messages,
// and user input requests
let mut get_requests: Vec<GetContractRequest> = Vec::new();
let mut put_requests: Vec<PutContractRequest> = Vec::new();
let mut update_requests: Vec<UpdateContractRequest> = Vec::new();
let mut subscribe_requests: Vec<SubscribeContractRequest> = Vec::new();
let mut delegate_messages: Vec<DelegateMessage> = Vec::new();
let mut user_input_requests: Vec<UserInputRequest<'static>> = Vec::new();
for msg in values {
match msg {
OutboundDelegateMsg::GetContractRequest(req) => {
get_requests.push(req);
}
OutboundDelegateMsg::PutContractRequest(req) => {
put_requests.push(req);
}
OutboundDelegateMsg::UpdateContractRequest(req) => {
update_requests.push(req);
}
OutboundDelegateMsg::SubscribeContractRequest(req) => {
subscribe_requests.push(req);
}
OutboundDelegateMsg::SendDelegateMessage(msg) => {
delegate_messages.push(msg);
}
OutboundDelegateMsg::RequestUserInput(req) => {
user_input_requests.push(req);
}
other @ OutboundDelegateMsg::ApplicationMessage(_)
| other @ OutboundDelegateMsg::ContextUpdated(_) => {
// Accumulate non-request messages
accumulated_messages.push(other);
}
}
}
// If no contract requests, delegate messages, or user input requests, we're done
if get_requests.is_empty()
&& put_requests.is_empty()
&& update_requests.is_empty()
&& subscribe_requests.is_empty()
&& delegate_messages.is_empty()
&& user_input_requests.is_empty()
{
return accumulated_messages;
}
let mut inbound_responses: Vec<InboundDelegateMsg<'static>> = Vec::new();
// Process PUT requests (fire-and-forget: upsert state, send result back).
// This calls upsert_contract_state which stores locally AND automatically
// propagates to the network via BroadcastStateChange — the same mechanism
// used by normal client PUT operations (ContractHandlerEvent::PutQuery).
if !put_requests.is_empty() {
tracing::debug!(
delegate_key = %delegate_key,
count = put_requests.len(),
"Processing PutContractRequest messages from delegate"
);
for req in put_requests {
let contract_key = req.contract.key();
let context = req.context;
let result = contract_handler
.executor()
.upsert_contract_state(
contract_key,
Either::Left(req.state),
req.related_contracts,
Some(req.contract),
)
.await;
let put_result = match result {
Ok(_) => Ok(()),
Err(err) => {
tracing::warn!(
contract = %contract_key,
error = %err,
"Failed to upsert contract for delegate PutContractRequest"
);
Err(format!("{err}"))
}
};
inbound_responses.push(InboundDelegateMsg::PutContractResponse(
PutContractResponse {
contract_id: *contract_key.id(),
result: put_result,
context,
},
));
}
}
// Process GET requests
if !get_requests.is_empty() {
tracing::debug!(
delegate_key = %delegate_key,
count = get_requests.len(),
"Processing GetContractRequest messages from delegate"
);
for req in get_requests {
let contract_id = req.contract_id;
let context = req.context;
// Look up the full key from the instance id
let state = match contract_handler.executor().lookup_key(&contract_id) {
Some(full_key) => {
// Fetch the contract state
match contract_handler
.executor()
.fetch_contract(full_key, false)
.await
{
Ok((state, _)) => state,
Err(err) => {
tracing::warn!(
contract = %contract_id,
error = %err,
"Failed to fetch contract for delegate GetContractRequest"
);
None
}
}
}
None => {
tracing::debug!(
contract = %contract_id,
"Contract not found locally for delegate GetContractRequest"
);
None
}
};
inbound_responses.push(InboundDelegateMsg::GetContractResponse(
GetContractResponse {
contract_id,
state,
context,
},
));
}
}
// Process UPDATE requests (fire-and-forget: apply update, send result back).
// Like PUT, this calls upsert_contract_state which propagates to the network
// automatically via BroadcastStateChange when the state actually changes.
// Only UpdateData::State and UpdateData::Delta are supported; compound variants
// (StateAndDelta, Related*) are rejected because the delegate API doesn't
// currently provide the related contract information needed to resolve them.
if !update_requests.is_empty() {
tracing::debug!(
delegate_key = %delegate_key,
count = update_requests.len(),
"Processing UpdateContractRequest messages from delegate"
);
for req in update_requests {
let contract_id = req.contract_id;
let context = req.context;
// Look up the full key from the instance id
let result = match contract_handler.executor().lookup_key(&contract_id) {
Some(full_key) => {
let update_value: Either<WrappedState, StateDelta<'static>> = match req
.update
{
freenet_stdlib::prelude::UpdateData::State(state) => {
Either::Left(WrappedState::from(state.into_bytes()))
}
freenet_stdlib::prelude::UpdateData::Delta(delta) => {
Either::Right(delta)
}
// StateAndDelta, RelatedState, RelatedDelta, RelatedStateAndDelta
// are not supported because the delegate API doesn't provide the
// related contract context needed to resolve them. Future
// `UpdateData` variants (the enum is `#[non_exhaustive]` since
// stdlib 0.6.0) fall through the same "unsupported" branch and
// are similarly rejected with a warn-level log.
other @ freenet_stdlib::prelude::UpdateData::StateAndDelta {
..
}
| other @ freenet_stdlib::prelude::UpdateData::RelatedState { .. }
| other @ freenet_stdlib::prelude::UpdateData::RelatedDelta { .. }
| other @ freenet_stdlib::prelude::UpdateData::RelatedStateAndDelta {
..
}
| other => {
tracing::warn!(
contract = %contract_id,
variant = ?std::mem::discriminant(&other),
"Unsupported UpdateData variant in delegate UpdateContractRequest \
(only State and Delta are supported)"
);
inbound_responses.push(InboundDelegateMsg::UpdateContractResponse(
UpdateContractResponse {
contract_id,
result: Err("Unsupported UpdateData variant".to_string()),
context,
},
));
continue;
}
};
contract_handler
.executor()
.upsert_contract_state(
full_key,
update_value,
RelatedContracts::default(),
None,
)
.await
}
None => {
tracing::debug!(
contract = %contract_id,
"Contract not found locally for delegate UpdateContractRequest"
);
inbound_responses.push(InboundDelegateMsg::UpdateContractResponse(
UpdateContractResponse {
contract_id,
result: Err("Contract not found".to_string()),
context,
},
));
continue;
}
};
let update_result = match result {
Ok(_) => Ok(()),
Err(err) => {
tracing::warn!(
contract = %contract_id,
error = %err,
"Failed to update contract for delegate UpdateContractRequest"
);
Err(format!("{err}"))
}
};
inbound_responses.push(InboundDelegateMsg::UpdateContractResponse(
UpdateContractResponse {
contract_id,
result: update_result,
context,
},
));
}
}
// Process SUBSCRIBE requests
// There are two registration paths that converge on DELEGATE_SUBSCRIPTIONS:
// 1. V2 delegates: subscribe_contract() host function (native_api.rs) registers
// during WASM execution and returns success/error synchronously.
// 2. V1 delegates: emit SubscribeContractRequest in process() outbound, handled here.
// Both paths are idempotent — inserting the same (contract_id, delegate_key) twice
// is a no-op on the HashSet. After registration, the delegate receives
// ContractNotification messages when the subscribed contract's state changes.
//
// TODO(#2830): UnsubscribeContractRequest is not yet handled. Delegates can
// only unsubscribe implicitly via UnregisterDelegate cleanup.
if !subscribe_requests.is_empty() {
tracing::debug!(
delegate_key = %delegate_key,
count = subscribe_requests.len(),
"Processing SubscribeContractRequest messages from delegate"
);
for req in subscribe_requests {
let contract_id = req.contract_id;
let context = req.context;
// Validate contract existence before registering (matches V2 host function behavior)
let result = if contract_handler
.executor()
.lookup_key(&contract_id)
.is_some()
{
// Register subscription in the global registry
crate::wasm_runtime::DELEGATE_SUBSCRIPTIONS
.entry(contract_id)
.or_default()
.insert(delegate_key.clone());
Ok(())
} else {
tracing::debug!(
contract = %contract_id,
"Contract not found locally for delegate SubscribeContractRequest"
);
Err("Contract not found".to_string())
};
inbound_responses.push(InboundDelegateMsg::SubscribeContractResponse(
SubscribeContractResponse {
contract_id,
result,
context,
},
));
}
}
// Deliver delegate-to-delegate messages (fire-and-forget, single-hop).
//
// Design notes:
// - Delivery is intentionally single-hop: if target delegate B emits its own
// SendDelegateMessage in response, it is filtered out (not delivered). This
// prevents infinite recursion between delegates. We use execute_delegate_request
// (not the full delivery loop) for the same reason.
// - Target delegate receives empty params because params are not stored in the
// delegate registry — they are passed per-request at the API layer. If a target
// delegate's process() relies on params, the caller must use ApplicationMessages
// directly. This is a known v1 limitation.
// - The caller's delegate key is passed as `caller_delegate` so the receiver
// sees `MessageOrigin::Delegate(caller_key)` and can authorize on it
// (issue #3860). The runtime attests this identity — the calling delegate
// cannot forge it.
// - Inter-delegate messaging only works via ApplicationMessages path; messages
// from handle_delegate_notification (contract state change callbacks) do not
// trigger delegate-to-delegate delivery.
if !delegate_messages.is_empty() {
tracing::debug!(
delegate_key = %delegate_key,
count = delegate_messages.len(),
"Delivering delegate-to-delegate messages"
);
for msg in delegate_messages {
let target_key = msg.target.clone();
let inbound = vec![InboundDelegateMsg::DelegateMessage(msg)];
let target_req = DelegateRequest::ApplicationMessages {
key: target_key.clone(),
params: Parameters::from(Vec::new()),
inbound,
};
match contract_handler
.executor()
.execute_delegate_request(target_req, None, Some(delegate_key))
.await
{
Ok(freenet_stdlib::client_api::HostResponse::DelegateResponse {
values,
..
}) => {
// Filter out SendDelegateMessage from target's output to enforce
// single-hop delivery. Only accumulate client-visible messages.
for value in values {
if !matches!(value, OutboundDelegateMsg::SendDelegateMessage(_)) {
accumulated_messages.push(value);
}
}
}
Ok(_) => {}
Err(err) => {
tracing::warn!(
target_delegate = %target_key,
error = %err,
"Failed to deliver delegate message (fire-and-forget)"
);
}
}
}
}
// Process UserInput requests: prompt the user and send responses back
if !user_input_requests.is_empty() {
tracing::debug!(
delegate_key = %delegate_key,
count = user_input_requests.len(),
"Processing UserInputRequest messages from delegate"
);
// The caller identity passed to the prompter is built from the
// executor's runtime context, NOT from anything the delegate could
// influence — so a malicious delegate cannot spoof another app's
// or delegate's identity in the structured fields the prompt UI
// renders. Today the only attested non-None caller is a web app
// (via `MessageOrigin::WebApp`); delegate-to-delegate attestation
// is tracked by #3860 and will appear here as a new variant.
//
// The actual mapping lives in `caller_identity_from_origin` so it
// can be unit-tested independently of the executor plumbing.
let caller = caller_identity_from_origin(origin_contract);
let delegate_key_str = delegate_key.to_string();
for req in user_input_requests {
let request_id = req.request_id;
let response = match prompter
.prompt(&req, &delegate_key_str, caller.clone())
.await
{
Some((_, response)) => response,
None => {
tracing::warn!(
request_id,
delegate = %delegate_key,
"User input request timed out or was denied"
);
// Send an empty response so the delegate knows the request
// was denied/timed out, rather than leaving it waiting forever.
ClientResponse::new(Vec::new())
}
};
inbound_responses.push(InboundDelegateMsg::UserResponse(UserInputResponse {
request_id,
response,
// UserInputRequest has no context field, so we use default.
// The delegate's actual context is maintained separately in
// the process_outbound loop in delegate.rs.
context: DelegateContext::default(),
}));
}
}
// Create a new request to send the responses back to the delegate
current_req = DelegateRequest::ApplicationMessages {
key: delegate_key.clone(),
inbound: inbound_responses,
params: current_params.clone(),
};
}
}
/// Receive a delegate notification from the optional channel.
/// Returns `std::future::pending()` if the channel is `None` or closed,
/// so the `tokio::select!` branch is effectively disabled.
async fn recv_delegate_notification(
rx: &mut Option<DelegateNotificationReceiver>,
) -> executor::DelegateNotification {
match rx {
Some(rx) => match rx.recv().await {
Some(n) => n,
None => std::future::pending().await,
},
None => std::future::pending().await,
}
}
/// Try to receive a delegate notification without blocking.
/// Returns `None` if the channel is `None`, closed, or has no pending notifications.
fn try_recv_delegate_notification(
rx: &mut Option<DelegateNotificationReceiver>,
) -> Option<executor::DelegateNotification> {
match rx {
Some(rx) => rx.try_recv().ok(),
None => None,
}
}
/// Build a `CallerIdentity` for the permission prompt UI from the executor's
/// runtime origin context (see #3857).
///
/// The mapping is intentionally narrow: today the only attested non-`None`
/// caller is a web app via `MessageOrigin::WebApp(..)`. Every other path
/// (delegate-to-delegate, local client, missing attestation) collapses to
/// `CallerIdentity::None` and renders as `"No app caller"` in the UI.
/// Issue #3860 tracks adding a `MessageOrigin::Delegate(DelegateKey)` variant
/// and the corresponding `CallerIdentity::Delegate` row; until that lands,
/// inter-delegate calls are not distinguishable here from "no caller at all".
///
/// Extracted as a free function (rather than inlined at the call site) so
/// the mapping can be unit-tested in isolation. Without this, swapping the
/// `Some` and `None` arms — or accidentally wiring a delegate-controlled
/// value into the prompter — would not fail any test.
fn caller_identity_from_origin(origin: Option<&ContractInstanceId>) -> CallerIdentity {
match origin {
Some(id) => CallerIdentity::WebApp(id.to_string()),
None => CallerIdentity::None,
}
}
pub(crate) async fn contract_handling<CH, P>(
mut contract_handler: CH,
prompter: P,
) -> Result<(), ContractError>
where
CH: ContractHandler + Send + 'static,
P: UserInputPrompter,
{
let mut delegate_rx = contract_handler.executor().take_delegate_notification_rx();
let mut fair_queue = fair_queue::FairEventQueue::new();
loop {
// Drain pending events from the channel into the fair queue (bounded batch).
// Capped at MAX_DRAIN_BATCH (256) to bound the synchronous work per iteration
// before yielding back to the Tokio scheduler. Each iteration of this loop is
// a non-blocking try_recv + HashMap insert, so 256 iterations complete in
// single-digit microseconds even at peak load.
for _ in 0..fair_queue::MAX_DRAIN_BATCH {
match contract_handler.channel().try_recv_from_sender()? {
Some((id, event)) => {
// Process ClientDisconnect inline — it's a lightweight cleanup
// operation that should never be delayed or compete with
// DelegateRequest events for the default queue's limited capacity.
if let ContractHandlerEvent::ClientDisconnect { client_id } = &event {
let client_id = *client_id;
contract_handler.executor().remove_client(client_id);
contract_handler.channel().drop_waiting_response(id);
continue;
}
if let Err(rejected) = fair_queue.try_push(id, event) {
send_queue_full_response(contract_handler.channel(), rejected).await;
}
}
None => break,
}
}
// Drain delegate notifications (non-blocking, bounded) even when the fair queue
// has work. This prevents delegate starvation under sustained contract load.
// We drain up to MAX_DELEGATE_DRAIN_BATCH to handle bursts (e.g., a contract
// update triggering many delegate notifications simultaneously).
for _ in 0..MAX_DELEGATE_DRAIN_BATCH {
match try_recv_delegate_notification(&mut delegate_rx) {
Some(notification) => {
handle_delegate_notification(&mut contract_handler, notification, &prompter)
.await;
}
None => break,
}
}
// Process one event from the fair queue (round-robin across contracts)
if let Some((id, event)) = fair_queue.pop() {
handle_contract_event(&mut contract_handler, id, event, &prompter).await?;
continue;
}
// Fair queue is empty — block-wait for a new event or delegate notification
tokio::select! {
result = contract_handler.channel().recv_from_sender() => {
let (id, event) = result?;
if let Err(rejected) = fair_queue.try_push(id, event) {
send_queue_full_response(contract_handler.channel(), rejected).await;
}
}
notification = recv_delegate_notification(&mut delegate_rx) => {
handle_delegate_notification(&mut contract_handler, notification, &prompter).await;
}
}
}
}
/// Send an error response to the event sender when the per-contract queue is full.
///
/// Logs a warning and sends the appropriate error response variant for the rejected event.
/// For fire-and-forget events (delegates, disconnects), no response is sent.
async fn send_queue_full_response(
channel: &mut handler::ContractHandlerChannel<handler::ContractHandlerHalve>,
rejected: Box<fair_queue::RejectedEvent>,
) {
tracing::warn!(
event = %rejected.event,
"Rejected event due to per-contract queue capacity limit"
);
let make_err = || ExecutorError::other(anyhow::anyhow!("contract queue full, try again later"));
let response = match &rejected.event {
ContractHandlerEvent::PutQuery { .. } => ContractHandlerEvent::PutResponse {
new_value: Err(make_err()),
state_changed: false,
},
ContractHandlerEvent::UpdateQuery { .. } => ContractHandlerEvent::UpdateResponse {
new_value: Err(make_err()),
state_changed: false,
},
ContractHandlerEvent::GetQuery { .. } => ContractHandlerEvent::GetResponse {
key: None,
response: Err(make_err()),
},
ContractHandlerEvent::GetSummaryQuery { key, .. } => {
ContractHandlerEvent::GetSummaryResponse {
key: *key,
summary: Err(make_err()),
}
}
ContractHandlerEvent::GetDeltaQuery { key, .. } => ContractHandlerEvent::GetDeltaResponse {
key: *key,
delta: Err(make_err()),
},
// Events without error response variants: drop the oneshot sender to
// unblock the caller. The caller's receiver will get a RecvError, which
// maps to ContractError::NoEvHandlerResponse. This prevents leaking
// entries in the waiting_response map.
ContractHandlerEvent::DelegateRequest { .. }
| ContractHandlerEvent::DelegateResponse(_)
| ContractHandlerEvent::PutResponse { .. }
| ContractHandlerEvent::GetResponse { .. }
| ContractHandlerEvent::UpdateResponse { .. }
| ContractHandlerEvent::UpdateNoChange { .. }
| ContractHandlerEvent::RegisterSubscriberListener { .. }
| ContractHandlerEvent::RegisterSubscriberListenerResponse
| ContractHandlerEvent::QuerySubscriptions { .. }
| ContractHandlerEvent::QuerySubscriptionsResponse
| ContractHandlerEvent::GetSummaryResponse { .. }
| ContractHandlerEvent::GetDeltaResponse { .. }
| ContractHandlerEvent::NotifySubscriptionError { .. }
| ContractHandlerEvent::NotifySubscriptionErrorResponse
| ContractHandlerEvent::ClientDisconnect { .. } => {
channel.drop_waiting_response(rejected.id);
return;
}
};
if let Err(error) = channel.send_to_sender(rejected.id, response).await {
tracing::warn!(
error = %error,
"Failed to send queue-full response (client may have disconnected)"
);
}
}
async fn handle_delegate_notification<CH, P>(
contract_handler: &mut CH,
notification: executor::DelegateNotification,
prompter: &P,
) where
CH: ContractHandler + Send + 'static,
P: UserInputPrompter,
{
let executor::DelegateNotification {
delegate_key,
contract_id,
new_state,
} = notification;
tracing::debug!(
delegate = %delegate_key,
contract = %contract_id,
"Delivering contract notification to delegate"
);
// Unwrap the Arc — if this is the last subscriber the state moves without cloning,
// otherwise a clone is made (unavoidable since ContractNotification owns the state).
let owned_state = Arc::try_unwrap(new_state).unwrap_or_else(|arc| (*arc).clone());
let inbound = vec![InboundDelegateMsg::ContractNotification(
ContractNotification {
contract_id,
new_state: owned_state,
context: DelegateContext::default(),
},
)];
let req = DelegateRequest::ApplicationMessages {
key: delegate_key.clone(),
params: Parameters::from(vec![]),
inbound,
};
let outbound = handle_delegate_with_contract_requests(
contract_handler,
req,
None,
&delegate_key,
prompter,
)
.await;
// TODO: Route outbound ApplicationMessages to subscribed apps #3275
// handle_delegate_with_contract_requests already processes contract requests
// (GET/PUT/UPDATE/SUBSCRIBE) internally. The remaining outbound messages are
// ApplicationMessages meant for connected apps, but notification-driven
// invocations have no originating client connection to route them to.
// When delegate-to-app notification routing is implemented, these should be
// forwarded to all apps registered with this delegate.
for msg in &outbound {
match msg {
OutboundDelegateMsg::ApplicationMessage(app_msg) => {
tracing::warn!(
delegate = %delegate_key,
payload_len = app_msg.payload.len(),
"Delegate produced ApplicationMessage from contract notification \
but no client routing is available yet — message dropped"
);
}
OutboundDelegateMsg::RequestUserInput(_)
| OutboundDelegateMsg::ContextUpdated(_)
| OutboundDelegateMsg::GetContractRequest(_)
| OutboundDelegateMsg::PutContractRequest(_)
| OutboundDelegateMsg::UpdateContractRequest(_)
| OutboundDelegateMsg::SubscribeContractRequest(_)
| OutboundDelegateMsg::SendDelegateMessage(_) => {
tracing::warn!(
delegate = %delegate_key,
msg_type = ?std::mem::discriminant(msg),
"Delegate produced unexpected outbound message from contract notification — dropped"
);
}
}
}
}
async fn handle_contract_event<CH, P>(
contract_handler: &mut CH,
id: handler::EventId,
event: ContractHandlerEvent,
prompter: &P,
) -> Result<(), ContractError>
where
CH: ContractHandler + Send + 'static,
P: UserInputPrompter,
{
tracing::debug!(
event = %event,
"Received contract handling event"
);
match event {
ContractHandlerEvent::GetQuery {
instance_id,
return_contract_code,
} => {
// Look up the full key from the instance_id
let key = contract_handler.executor().lookup_key(&instance_id);
match key {
Some(key) => {
match contract_handler
.executor()
.fetch_contract(key, return_contract_code)
.instrument(
tracing::info_span!("fetch_contract", %key, %return_contract_code),
)
.await
{
Ok((state, contract)) => {
tracing::debug!(
contract = %key,
with_contract_code = return_contract_code,
has_contract = contract.is_some(),
has_state = state.is_some(),
phase = "get_complete",
"Fetched contract"
);
// Send response back to caller. If the caller disconnected, just log and continue.
if let Err(error) = contract_handler
.channel()
.send_to_sender(
id,
ContractHandlerEvent::GetResponse {
key: Some(key),
response: Ok(StoreResponse { state, contract }),
},
)
.await
{
tracing::debug!(
error = %error,
contract = %key,
"Failed to send GET response (client may have disconnected)"
);
}
}
Err(err) => {
tracing::warn!(
contract = %key,
error = %err,
phase = "get_failed",
"Error executing get contract query"
);
if err.is_fatal() {
tracing::error!(
contract = %key,
error = %err,
phase = "fatal_error",
"Fatal executor error during get query"
);
return Err(ContractError::FatalExecutorError { key, error: err });
}
// Send error response back to caller. If the caller disconnected, just log and continue.
if let Err(error) = contract_handler
.channel()
.send_to_sender(
id,
ContractHandlerEvent::GetResponse {
key: Some(key),
response: Err(err),
},
)
.await
{
tracing::debug!(
error = %error,
contract = %key,
"Failed to send GET error response (client may have disconnected)"
);
}
}
}
}
None => {
// Contract not found locally - return None for key
tracing::debug!(
instance_id = %instance_id,
phase = "not_found",
"Contract not found in local store"
);
if let Err(error) = contract_handler
.channel()
.send_to_sender(
id,
ContractHandlerEvent::GetResponse {
key: None,
response: Ok(StoreResponse {
state: None,
contract: None,
}),
},
)
.await
{
tracing::debug!(
error = %error,
instance_id = %instance_id,
"Failed to send GET not-found response (client may have disconnected)"
);
}
}
}
}
ContractHandlerEvent::PutQuery {
key,
state,
related_contracts,
contract,
} => {
// DEBUG: Log contract details in PutQuery handler
if let Some(ref contract_container) = contract {
tracing::debug!(
contract = %key,
key_code_hash = ?key.code_hash(),
container_key = %contract_container.key(),
container_code_hash = ?contract_container.key().code_hash(),
data_len = contract_container.data().len(),
phase = "put_query_debug",
"DEBUG PUT: In PutQuery handler with contract"
);
} else {
tracing::debug!(
contract = %key,
phase = "put_query_debug",
"DEBUG PUT: In PutQuery handler - contract is None"
);
}
let put_result = contract_handler
.executor()
.upsert_contract_state(
key,
Either::Left(state.clone()),
related_contracts,
contract,
)
.instrument(tracing::info_span!("upsert_contract_state", %key))
.await;
let event_result = match put_result {
Ok(UpsertResult::NoChange) => ContractHandlerEvent::PutResponse {
new_value: Ok(state),
state_changed: false,
},
Ok(UpsertResult::Updated(new_state)) => ContractHandlerEvent::PutResponse {
new_value: Ok(new_state),
state_changed: true,
},
Ok(UpsertResult::CurrentWon(current_state)) => {
// Merge resulted in no change (incoming state was old/already incorporated).
ContractHandlerEvent::PutResponse {
new_value: Ok(current_state),
state_changed: false,
}
}
Err(err) => {
if err.is_fatal() {
tracing::error!(
contract = %key,
error = %err,
phase = "fatal_error",
"Fatal executor error during put query"
);
return Err(ContractError::FatalExecutorError { key, error: err });
}
ContractHandlerEvent::PutResponse {
new_value: Err(err),
state_changed: false,
}
}
};
// Send response back to caller. If the caller disconnected (e.g., WebSocket closed),
// the response channel may be dropped. This is not fatal - the contract has already
// been stored, so we just log and continue processing other events.
if let Err(error) = contract_handler
.channel()
.send_to_sender(id, event_result)
.await
{
tracing::debug!(
error = %error,
contract = %key,
"Failed to send PUT response (client may have disconnected)"
);
}
}
ContractHandlerEvent::UpdateQuery {
key,
data,
related_contracts,
} => {
let update_value: Either<WrappedState, StateDelta<'static>> = match data {
freenet_stdlib::prelude::UpdateData::State(state) => {
Either::Left(WrappedState::from(state.into_bytes()))
}
freenet_stdlib::prelude::UpdateData::Delta(delta) => Either::Right(delta),
freenet_stdlib::prelude::UpdateData::StateAndDelta { .. }
| freenet_stdlib::prelude::UpdateData::RelatedState { .. }
| freenet_stdlib::prelude::UpdateData::RelatedDelta { .. }
| freenet_stdlib::prelude::UpdateData::RelatedStateAndDelta { .. } => {
unreachable!()
}
// `UpdateData` is `#[non_exhaustive]` since stdlib 0.6.0.
// Future variants must be explicitly handled before they
// flow through `UpdateQuery`; the producer at the edge
// should reject unknown variants rather than routing them
// here.
_ => unreachable!(
"Unknown UpdateData variant reached ContractHandlerEvent::UpdateQuery; \
add explicit handling before landing the new variant upstream"
),
};
let update_result = contract_handler
.executor()
.upsert_contract_state(key, update_value, related_contracts, None)
.instrument(tracing::info_span!("upsert_contract_state", %key))
.await;
let event_result = match update_result {
Ok(UpsertResult::NoChange) => {
tracing::debug!(
contract = %key,
phase = "update_no_change",
"UPDATE resulted in NoChange, fetching current state to return UpdateResponse"
);
// When there's no change, we still need to return the current state
// so the client gets a proper response
match contract_handler.executor().fetch_contract(key, false).await {
Ok((Some(current_state), _)) => {
tracing::debug!(
contract = %key,
phase = "fetch_complete",
"Successfully fetched current state for NoChange update"
);
ContractHandlerEvent::UpdateResponse {
new_value: Ok(current_state),
state_changed: false,
}
}
Ok((None, _)) => {
tracing::warn!(
contract = %key,
phase = "fetch_failed",
"No state found when fetching for NoChange update"
);
// Fallback to the old behavior if we can't fetch the state
ContractHandlerEvent::UpdateNoChange { key }
}
Err(err) => {
tracing::error!(
contract = %key,
error = %err,
phase = "fetch_error",
"Error fetching state for NoChange update"
);
// Fallback to the old behavior if we can't fetch the state
ContractHandlerEvent::UpdateNoChange { key }
}
}
}
Ok(UpsertResult::Updated(state)) => ContractHandlerEvent::UpdateResponse {
new_value: Ok(state),
state_changed: true,
},
Ok(UpsertResult::CurrentWon(current_state)) => {
// Merge resulted in no change (incoming state was old/already incorporated).
// Return current state with state_changed=false.
ContractHandlerEvent::UpdateResponse {
new_value: Ok(current_state),
state_changed: false,
}
}
Err(err) => {
if err.is_fatal() {
tracing::error!(
contract = %key,
error = %err,
phase = "fatal_error",
"Fatal executor error during update query"
);
return Err(ContractError::FatalExecutorError { key, error: err });
}
ContractHandlerEvent::UpdateResponse {
new_value: Err(err),
state_changed: false,
}
}
};
// Send response back to caller. If the caller disconnected, the response channel
// may be dropped. This is not fatal - the update has already been applied.
if let Err(error) = contract_handler
.channel()
.send_to_sender(id, event_result)
.await
{
tracing::debug!(
error = %error,
contract = %key,
"Failed to send UPDATE response (client may have disconnected)"
);
}
}
ContractHandlerEvent::DelegateRequest {
req,
origin_contract,
} => {
let delegate_key = req.key().clone();
tracing::debug!(
delegate_key = %delegate_key,
?origin_contract,
"Processing delegate request"
);
// Execute the delegate and handle any GetContractRequest messages
let response = handle_delegate_with_contract_requests(
contract_handler,
req,
origin_contract.as_ref(),
&delegate_key,
prompter,
)
.await;
// Send response back to caller. If the caller disconnected, the response channel
// may be dropped. This is not fatal - the delegate has already been processed.
if let Err(error) = contract_handler
.channel()
.send_to_sender(id, ContractHandlerEvent::DelegateResponse(response))
.await
{
tracing::debug!(
error = %error,
delegate_key = %delegate_key,
"Failed to send DELEGATE response (client may have disconnected)"
);
}
}
ContractHandlerEvent::RegisterSubscriberListener {
key,
client_id,
summary,
subscriber_listener,
} => {
if let Err(err) = contract_handler.executor().register_contract_notifier(
key,
client_id,
subscriber_listener,
summary,
) {
tracing::warn!(
contract = %key,
client = %client_id,
error = %err,
phase = "registration_failed",
"Error registering subscriber listener"
);
}
// FIXME: if there is an error send actually an error back
// If the caller disconnected, just log and continue.
if let Err(error) = contract_handler
.channel()
.send_to_sender(id, ContractHandlerEvent::RegisterSubscriberListenerResponse)
.await
{
tracing::debug!(
error = %error,
contract = %key,
"Failed to send RegisterSubscriberListener response (client may have disconnected)"
);
}
}
ContractHandlerEvent::NotifySubscriptionError { key, reason } => {
contract_handler
.executor()
.notify_subscription_error(key, reason);
if let Err(error) = contract_handler
.channel()
.send_to_sender(id, ContractHandlerEvent::NotifySubscriptionErrorResponse)
.await
{
tracing::debug!(
error = %error,
contract = %key,
"Failed to send NotifySubscriptionError response"
);
}
}
ContractHandlerEvent::QuerySubscriptions { callback } => {
// Get subscription information from the executor and send it through the callback
let subscriptions = contract_handler.executor().get_subscription_info();
let connections = vec![]; // For now, we'll populate this from the calling context
let network_debug = crate::message::NetworkDebugInfo {
application_subscriptions: subscriptions,
network_subscriptions: vec![], // Contract handler only tracks application subscriptions
connected_peers: connections,
};
if let Err(e) = callback
.send(crate::message::QueryResult::NetworkDebug(network_debug))
.await
{
tracing::debug!(error = %e, "failed to send network debug info via callback");
}
// If the caller disconnected, just log and continue.
if let Err(error) = contract_handler
.channel()
.send_to_sender(id, ContractHandlerEvent::QuerySubscriptionsResponse)
.await
{
tracing::debug!(
error = %error,
"Failed to send QuerySubscriptions response (client may have disconnected)"
);
}
}
ContractHandlerEvent::GetSummaryQuery { key } => {
let summary = contract_handler
.executor()
.summarize_contract_state(key)
.instrument(tracing::info_span!("summarize_contract_state", %key))
.await;
if let Err(error) = contract_handler
.channel()
.send_to_sender(
id,
ContractHandlerEvent::GetSummaryResponse { key, summary },
)
.await
{
tracing::debug!(
error = %error,
contract = %key,
"Failed to send GetSummary response (client may have disconnected)"
);
}
}
ContractHandlerEvent::GetDeltaQuery { key, their_summary } => {
let delta = contract_handler
.executor()
.get_contract_state_delta(key, their_summary)
.instrument(tracing::info_span!("get_contract_state_delta", %key))
.await;
if let Err(error) = contract_handler
.channel()
.send_to_sender(id, ContractHandlerEvent::GetDeltaResponse { key, delta })
.await
{
tracing::debug!(
error = %error,
contract = %key,
"Failed to send GetDelta response (client may have disconnected)"
);
}
}
ContractHandlerEvent::ClientDisconnect { client_id } => {
contract_handler.executor().remove_client(client_id);
contract_handler.channel().drop_waiting_response(id);
}
ContractHandlerEvent::DelegateResponse(_)
| ContractHandlerEvent::PutResponse { .. }
| ContractHandlerEvent::GetResponse { .. }
| ContractHandlerEvent::UpdateResponse { .. }
| ContractHandlerEvent::UpdateNoChange { .. }
| ContractHandlerEvent::RegisterSubscriberListenerResponse
| ContractHandlerEvent::QuerySubscriptionsResponse
| ContractHandlerEvent::GetSummaryResponse { .. }
| ContractHandlerEvent::GetDeltaResponse { .. }
| ContractHandlerEvent::NotifySubscriptionErrorResponse => {
unreachable!("response events should not be received by the handler")
}
}
Ok(())
}
#[derive(Debug, thiserror::Error)]
pub(crate) enum ContractError {
#[error("handler channel dropped")]
ChannelDropped(Box<ContractHandlerEvent>),
#[error("{0}")]
IOError(#[from] std::io::Error),
#[error("no response received from handler")]
NoEvHandlerResponse,
#[error("fatal executor error for contract {key}: {error}")]
FatalExecutorError {
key: ContractKey,
error: ExecutorError,
},
}
#[cfg(test)]
#[allow(clippy::wildcard_enum_match_arm)]
mod tests {
use super::*;
use crate::config::GlobalExecutor;
use std::time::Duration;
fn make_contract_key() -> ContractKey {
let code = ContractCode::from(vec![42u8; 32]);
let params = Parameters::from(vec![7u8; 8]);
ContractKey::from_params_and_code(¶ms, &code)
}
// Regression test for issue #3857: the executor's origin context must be
// mapped onto the prompter's CallerIdentity correctly. Without this test,
// accidentally swapping the Some/None arms — or wiring the wrong
// variable into the prompter call — would not fail any other test in
// the suite (the prompter unit tests pass `CallerIdentity` in directly).
#[test]
fn test_caller_identity_from_origin() {
// None origin (delegate-to-delegate, local client, missing
// attestation) collapses to CallerIdentity::None.
assert_eq!(caller_identity_from_origin(None), CallerIdentity::None);
// Some(ContractInstanceId) becomes CallerIdentity::WebApp(<id>),
// with the id stringified via its Display impl.
let key = make_contract_key();
let id = *key.id();
let mapped = caller_identity_from_origin(Some(&id));
assert_eq!(mapped, CallerIdentity::WebApp(id.to_string()));
// Sanity check: the produced string must not be empty (would
// render as "Freenet app " with a dangling space in the UI).
match mapped {
CallerIdentity::WebApp(s) => assert!(!s.is_empty()),
other => panic!("expected WebApp, got {other:?}"),
}
}
/// Helper: send an event through the sender halve and receive it on the handler side,
/// then wrap it as a RejectedEvent. This simulates the normal drain path where
/// try_recv_from_sender inserts into waiting_response, followed by queue rejection.
async fn setup_rejected_event(
send_halve: handler::ContractHandlerChannel<handler::SenderHalve>,
rcv_halve: &mut handler::ContractHandlerChannel<handler::ContractHandlerHalve>,
event: ContractHandlerEvent,
) -> (
Box<fair_queue::RejectedEvent>,
tokio::task::JoinHandle<Result<ContractHandlerEvent, anyhow::Error>>,
) {
// Spawn the sender — it blocks until the response arrives
let handle = GlobalExecutor::spawn(async move {
send_halve
.send_to_handler(event)
.await
.map_err(|e| anyhow::anyhow!("{e}"))
});
// Receive on the handler side (populates waiting_response)
let (id, received_event) =
tokio::time::timeout(Duration::from_millis(200), rcv_halve.recv_from_sender())
.await
.expect("timeout waiting for event")
.expect("channel should be open");
let rejected = Box::new(fair_queue::RejectedEvent {
id,
event: received_event,
});
(rejected, handle)
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn send_queue_full_response_put_query() {
let (send_halve, mut rcv_halve, _) = handler::contract_handler_channel();
let key = make_contract_key();
let (rejected, handle) = setup_rejected_event(
send_halve,
&mut rcv_halve,
ContractHandlerEvent::PutQuery {
key,
state: WrappedState::new(vec![1, 2, 3]),
related_contracts: RelatedContracts::default(),
contract: None,
},
)
.await;
send_queue_full_response(&mut rcv_halve, rejected).await;
let response = tokio::time::timeout(Duration::from_millis(200), handle)
.await
.expect("timeout")
.expect("task should complete")
.expect("should get response");
match response {
ContractHandlerEvent::PutResponse {
new_value,
state_changed,
} => {
assert!(new_value.is_err(), "should be an error response");
assert!(!state_changed);
}
other => panic!("expected PutResponse, got {other}"),
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn send_queue_full_response_get_query() {
let (send_halve, mut rcv_halve, _) = handler::contract_handler_channel();
let key = make_contract_key();
let (rejected, handle) = setup_rejected_event(
send_halve,
&mut rcv_halve,
ContractHandlerEvent::GetQuery {
instance_id: *key.id(),
return_contract_code: false,
},
)
.await;
send_queue_full_response(&mut rcv_halve, rejected).await;
let response = tokio::time::timeout(Duration::from_millis(200), handle)
.await
.expect("timeout")
.expect("task should complete")
.expect("should get response");
match response {
ContractHandlerEvent::GetResponse { response, .. } => {
assert!(response.is_err(), "should be an error response");
}
other => panic!("expected GetResponse, got {other}"),
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn send_queue_full_response_update_query() {
let (send_halve, mut rcv_halve, _) = handler::contract_handler_channel();
let key = make_contract_key();
let (rejected, handle) = setup_rejected_event(
send_halve,
&mut rcv_halve,
ContractHandlerEvent::UpdateQuery {
key,
data: UpdateData::Delta(StateDelta::from(vec![1])),
related_contracts: RelatedContracts::default(),
},
)
.await;
send_queue_full_response(&mut rcv_halve, rejected).await;
let response = tokio::time::timeout(Duration::from_millis(200), handle)
.await
.expect("timeout")
.expect("task should complete")
.expect("should get response");
match response {
ContractHandlerEvent::UpdateResponse {
new_value,
state_changed,
} => {
assert!(new_value.is_err(), "should be an error response");
assert!(!state_changed);
}
other => panic!("expected UpdateResponse, got {other}"),
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn send_queue_full_response_get_summary_query() {
let (send_halve, mut rcv_halve, _) = handler::contract_handler_channel();
let key = make_contract_key();
let (rejected, handle) = setup_rejected_event(
send_halve,
&mut rcv_halve,
ContractHandlerEvent::GetSummaryQuery { key },
)
.await;
send_queue_full_response(&mut rcv_halve, rejected).await;
let response = tokio::time::timeout(Duration::from_millis(200), handle)
.await
.expect("timeout")
.expect("task should complete")
.expect("should get response");
match response {
ContractHandlerEvent::GetSummaryResponse {
key: resp_key,
summary,
} => {
assert_eq!(resp_key, key);
assert!(summary.is_err(), "should be an error response");
}
other => panic!("expected GetSummaryResponse, got {other}"),
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn send_queue_full_response_get_delta_query() {
let (send_halve, mut rcv_halve, _) = handler::contract_handler_channel();
let key = make_contract_key();
let (rejected, handle) = setup_rejected_event(
send_halve,
&mut rcv_halve,
ContractHandlerEvent::GetDeltaQuery {
key,
their_summary: StateSummary::from(vec![1, 2]),
},
)
.await;
send_queue_full_response(&mut rcv_halve, rejected).await;
let response = tokio::time::timeout(Duration::from_millis(200), handle)
.await
.expect("timeout")
.expect("task should complete")
.expect("should get response");
match response {
ContractHandlerEvent::GetDeltaResponse {
key: resp_key,
delta,
} => {
assert_eq!(resp_key, key);
assert!(delta.is_err(), "should be an error response");
}
other => panic!("expected GetDeltaResponse, got {other}"),
}
}
/// Verify that fire-and-forget events (RegisterSubscriberListener, delegates, etc.)
/// have their waiting_response entry cleaned up via drop_waiting_response when rejected.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn send_queue_full_response_fire_and_forget_cleans_waiting_response() {
let (send_halve, mut rcv_halve, _) = handler::contract_handler_channel();
let key = make_contract_key();
let (rejected, handle) = setup_rejected_event(
send_halve,
&mut rcv_halve,
ContractHandlerEvent::RegisterSubscriberListener {
key: *key.id(),
client_id: crate::client_events::ClientId::next(),
summary: None,
subscriber_listener: tokio::sync::mpsc::channel(64).0,
},
)
.await;
// Verify waiting_response was populated
assert!(
rcv_halve.has_waiting_response(&rejected.id),
"waiting_response should contain the event"
);
let rejected_id = handler::EventId { id: rejected.id.id };
send_queue_full_response(&mut rcv_halve, rejected).await;
// Verify waiting_response was cleaned up
assert!(
!rcv_halve.has_waiting_response(&rejected_id),
"waiting_response should be cleaned up after rejection"
);
// The sender should get a RecvError (NoEvHandlerResponse) since we dropped the oneshot
let result = tokio::time::timeout(Duration::from_millis(200), handle)
.await
.expect("timeout")
.expect("task should complete");
assert!(
result.is_err(),
"fire-and-forget rejection should produce an error"
);
}
}