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
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
//! # TCP Handler
//!
//! Provides raw TCP networking capabilities to WebAssembly actors in the Theater system.
//! This handler is deliberately minimal — it moves bytes across the boundary and leaves
//! all protocol complexity (framing, routing, addressing) to actor-space code.
//!
//! ## Connection Handoff
//!
//! Connections can be transferred between actors for the "accept and hand off" pattern:
//!
//! 1. Acceptor calls `accept()` - connection starts in PENDING state
//! 2. Acceptor spawns a worker actor
//! 3. Acceptor calls `transfer(conn_id, worker_id)` - atomically transfers and activates
//! 4. Worker receives `handle-connection` callback and can immediately send/receive
//!
//! This prevents race conditions where data arrives before the handoff completes.
//!
//! ## Data Modes (Erlang-style)
//!
//! Connections support three data modes via `set-active()`:
//!
//! - `"passive"` (default): Data received only via explicit `receive()` calls
//! - `"active"`: Data pushed to actor via `on-data` callback continuously
//! - `"once"`: Single `on-data` callback, then switches back to passive
//!
//! This matches Erlang/OTP's `{active, true/false/once}` socket options.
//!
//! ## TLS Support
//!
//! TLS can be enabled via manifest configuration:
//!
//! ```toml
//! [[handler]]
//! type = "tcp"
//!
//! [handler.client_tls]
//! enabled = true
//! # ca_cert = "/path/to/ca.pem" # Optional custom CA
//! # skip_verify = false # For development only
//!
//! [handler.server_tls]
//! enabled = true
//! cert = "/path/to/server.pem"
//! key = "/path/to/server-key.pem"
//! ```
//!
//! When TLS is configured, connections are automatically encrypted. The actor
//! code doesn't need to change - it uses the same `tcp-connect`, `tcp-listen`,
//! `tcp-read`, `tcp-write` interface.
mod stream;
mod tls;
use std::collections::HashMap;
use std::future::Future;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::Mutex;
use tokio_util::sync::CancellationToken;
use tracing::{debug, error, info, warn};
use stream::{UnifiedReadHalf, UnifiedStream, UnifiedWriteHalf};
use tls::TlsContext;
use theater::actor::handle::ActorHandle;
use theater::actor::store::ActorStore;
use theater::config::actor_manifest::{HandlerConfig, TcpHandlerConfig};
use theater::handler::{Handler, HandlerContext, SharedActorInstance};
use theater::id::TheaterId;
use theater::shutdown::ShutdownReceiver;
use theater::pack_bridge::{
parse_pact, AsyncCtx, HostLinkerBuilder, InterfaceImpl, LinkerError, TypeHash, Value, ValueType,
};
// ============================================================================
// Interface Declarations
// ============================================================================
/// Embedded tcp.pact file content
const TCP_PACT: &str = include_str!("../tcp.pact");
/// Declare the theater:simple/tcp interface from the pact file.
fn tcp_interface() -> InterfaceImpl {
let pact = parse_pact(TCP_PACT).expect("embedded tcp.pact should be valid");
InterfaceImpl::from_pact(&pact)
}
// ============================================================================
// Connection State
// ============================================================================
/// State of a connection in its lifecycle
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ConnectionState {
/// Connection accepted but not yet activated - no data operations allowed
Pending,
/// Connection is active - send/receive allowed
Active,
}
/// Data mode for receiving data (Erlang-style)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DataMode {
/// Data only received via explicit receive() calls
Passive,
/// Data pushed to on-data callback continuously
Active,
/// Receive one chunk via on-data, then switch to Passive
Once,
}
/// Represents the stream state based on data mode
enum StreamState {
/// Full stream available for passive mode operations
Full(Box<UnifiedStream>),
/// Only write half available - read half taken by active mode task
WriteOnly(UnifiedWriteHalf),
/// Connection closed or stream taken
Closed,
}
/// A tracked TCP connection with ownership and state.
///
/// `stream` is wrapped in `Arc<Mutex<...>>` so the outer connections map
/// mutex is only held briefly for lookup/metadata. The actual I/O acquires
/// the per-connection lock — this lets two actors do I/O on different
/// connections in parallel, which is essential for any flow where the
/// runtime hosts both sides of a TCP conversation (e.g. an outbound SMTP
/// client talking to a local SMTP server in the same theater instance).
struct ConnectionEntry {
stream: Arc<Mutex<StreamState>>,
peer_addr: SocketAddr,
owner: TheaterId,
state: ConnectionState,
data_mode: DataMode,
}
/// A tracked TCP listener with ownership
struct ListenerEntry {
listener: TcpListener,
owner: TheaterId,
}
/// Shared TCP state across all actor instances.
///
/// This state is shared via Arc, so all TcpHandler instances in a Theater
/// runtime see the same connections and listeners. This enables connection
/// transfer between actors.
struct SharedTcpState {
connections: Mutex<HashMap<u64, ConnectionEntry>>,
listeners: Mutex<HashMap<u64, ListenerEntry>>,
next_id: AtomicU64,
max_connections: Option<u32>,
}
impl SharedTcpState {
fn new(max_connections: Option<u32>) -> Self {
Self {
connections: Mutex::new(HashMap::new()),
listeners: Mutex::new(HashMap::new()),
next_id: AtomicU64::new(1),
max_connections,
}
}
fn next_id(&self) -> u64 {
self.next_id.fetch_add(1, Ordering::Relaxed)
}
async fn check_connection_limit(&self) -> Result<(), Value> {
if let Some(max) = self.max_connections {
let count = self.connections.lock().await.len();
if count >= max as usize {
return Err(Value::String(format!(
"Connection limit reached ({}/{})",
count, max
)));
}
}
Ok(())
}
}
// ============================================================================
// Handler Implementation
// ============================================================================
/// Handler for providing raw TCP networking access to WebAssembly actors.
#[derive(Clone)]
pub struct TcpHandler {
config: TcpHandlerConfig,
/// Shared state across all handler instances - enables connection transfer
shared_state: Arc<SharedTcpState>,
/// Actor ID for this handler instance - set during setup
actor_id: Arc<std::sync::Mutex<Option<TheaterId>>>,
/// Actor handle for calling export functions (set in setup, used by listen)
actor_handle: Arc<std::sync::Mutex<Option<ActorHandle>>>,
/// Cancellation token for spawned background tasks
cancellation_token: CancellationToken,
/// TLS context for encrypted connections (shared across clones)
tls_context: Arc<Option<TlsContext>>,
}
impl TcpHandler {
pub fn new(config: TcpHandlerConfig) -> Self {
// Build TLS context from config
let tls_context = match TlsContext::from_config(&config) {
Ok(ctx) => Arc::new(ctx),
Err(e) => {
error!("Failed to build TLS context: {}. TLS will be disabled.", e);
Arc::new(None)
}
};
Self {
config,
shared_state: Arc::new(SharedTcpState::new(None)),
actor_id: Arc::new(std::sync::Mutex::new(None)),
actor_handle: Arc::new(std::sync::Mutex::new(None)),
cancellation_token: CancellationToken::new(),
tls_context,
}
}
/// Get the interface declarations for this handler.
pub fn interfaces(&self) -> Vec<InterfaceImpl> {
vec![tcp_interface()]
}
}
// ── Value parsing helpers ─────────────────────────────────────────────────
fn parse_string(input: &Value) -> Result<String, Value> {
match input {
Value::String(s) => Ok(s.clone()),
Value::Tuple(fields) if fields.len() == 1 => match &fields[0] {
Value::String(s) => Ok(s.clone()),
_ => Err(Value::String("Expected string".to_string())),
},
_ => Err(Value::String("Expected string".to_string())),
}
}
fn parse_two_strings(input: &Value) -> Result<(String, String), Value> {
match input {
Value::Tuple(fields) if fields.len() == 2 => {
let a = match &fields[0] {
Value::String(s) => s.clone(),
_ => return Err(Value::String("Expected string for first arg".to_string())),
};
let b = match &fields[1] {
Value::String(s) => s.clone(),
_ => return Err(Value::String("Expected string for second arg".to_string())),
};
Ok((a, b))
}
_ => Err(Value::String("Expected tuple (string, string)".to_string())),
}
}
fn parse_string_and_bytes(input: &Value) -> Result<(String, Vec<u8>), Value> {
match input {
Value::Tuple(fields) if fields.len() == 2 => {
let id = match &fields[0] {
Value::String(s) => s.clone(),
_ => return Err(Value::String("Expected string for id".to_string())),
};
let data = match &fields[1] {
Value::List { items, .. } => items
.iter()
.filter_map(|v| match v {
Value::U8(b) => Some(*b),
_ => None,
})
.collect::<Vec<u8>>(),
_ => return Err(Value::String("Expected list<u8> for data".to_string())),
};
Ok((id, data))
}
_ => Err(Value::String("Expected tuple (id, data)".to_string())),
}
}
fn parse_string_and_u32(input: &Value) -> Result<(String, u32), Value> {
match input {
Value::Tuple(fields) if fields.len() == 2 => {
let id = match &fields[0] {
Value::String(s) => s.clone(),
_ => return Err(Value::String("Expected string for id".to_string())),
};
let n = match &fields[1] {
Value::U32(n) => *n,
_ => return Err(Value::String("Expected u32".to_string())),
};
Ok((id, n))
}
_ => Err(Value::String("Expected tuple (id, u32)".to_string())),
}
}
fn id_to_string(id: u64) -> String {
id.to_string()
}
fn string_to_id(s: &str) -> Result<u64, Value> {
s.parse::<u64>()
.map_err(|_| Value::String(format!("Invalid id: {}", s)))
}
// ── Handler implementation ────────────────────────────────────────────────
impl Handler for TcpHandler {
fn create_instance(&self, config: Option<&HandlerConfig>) -> Box<dyn Handler> {
let tcp_config = match config {
Some(HandlerConfig::Tcp { config }) => config.clone(),
_ => self.config.clone(),
};
// Build TLS context from config if different from current
let tls_context = if config.is_some() {
// New config provided, rebuild TLS context
match TlsContext::from_config(&tcp_config) {
Ok(ctx) => Arc::new(ctx),
Err(e) => {
error!("Failed to build TLS context: {}. TLS will be disabled.", e);
Arc::new(None)
}
}
} else {
// Reuse existing TLS context
self.tls_context.clone()
};
// Share the same state across all instances - this is the key for transfer!
// Each instance gets its own cancellation token (cancelled when that actor shuts down)
Box::new(TcpHandler {
config: tcp_config,
shared_state: self.shared_state.clone(), // Same Arc!
actor_id: Arc::new(std::sync::Mutex::new(None)),
actor_handle: Arc::new(std::sync::Mutex::new(None)),
cancellation_token: CancellationToken::new(),
tls_context,
})
}
fn name(&self) -> &str {
"tcp"
}
fn imports(&self) -> Option<Vec<String>> {
Some(
self.interfaces()
.iter()
.map(|i| i.name().to_string())
.collect(),
)
}
fn exports(&self) -> Option<Vec<String>> {
Some(vec!["theater:simple/tcp-client".to_string()])
}
fn interface_hashes(&self) -> Vec<(String, TypeHash)> {
self.interfaces()
.iter()
.map(|i| (i.name().to_string(), i.hash()))
.collect()
}
fn interfaces(&self) -> Vec<theater::pack_bridge::InterfaceImpl> {
vec![tcp_interface()]
}
fn setup(
&mut self,
actor_handle: ActorHandle,
_actor_instance: SharedActorInstance,
shutdown_receiver: ShutdownReceiver,
_event_rx: tokio::sync::broadcast::Receiver<theater::chain::ChainEvent>,
) -> Pin<Box<dyn Future<Output = anyhow::Result<()>> + Send>> {
info!("TCP handler setup (passive mode)");
// Store the actor_handle for use by listen()
{
let mut handle_guard = self.actor_handle.lock().unwrap();
*handle_guard = Some(actor_handle);
}
// Get cancellation token to cancel on shutdown
let cancel_token = self.cancellation_token.clone();
let shared_state = self.shared_state.clone();
// Wait for shutdown, then clean up all resources
Box::pin(async move {
info!("TCP handler setup waiting for shutdown signal");
shutdown_receiver.wait_for_shutdown().await;
info!("TCP handler received shutdown, cleaning up resources");
// Cancel all spawned background tasks (listeners, active mode readers)
cancel_token.cancel();
info!("TCP handler cancellation token cancelled");
// Close all connections - clearing the map drops the streams
{
let mut connections = shared_state.connections.lock().await;
let conn_count = connections.len();
connections.clear();
if conn_count > 0 {
info!("TCP handler closed {} connections", conn_count);
}
}
// Close all listeners - clearing the map drops the TcpListeners
{
let mut listeners = shared_state.listeners.lock().await;
let listener_count = listeners.len();
listeners.clear();
if listener_count > 0 {
info!("TCP handler closed {} listeners", listener_count);
}
}
info!("TCP handler shutdown complete");
Ok(())
})
}
fn setup_host_functions_composite(
&mut self,
builder: &mut HostLinkerBuilder<'_, ActorStore>,
ctx: &mut HandlerContext,
) -> Result<(), LinkerError> {
info!("Setting up TCP host functions (Pack)");
if ctx.is_satisfied("theater:simple/tcp") {
info!("theater:simple/tcp already satisfied, skipping");
return Ok(());
}
// Get actor ID from context
let actor_id = ctx
.actor_id
.expect("actor_id should be set in HandlerContext");
// Store actor_id for this instance
{
let mut id_guard = self.actor_id.lock().unwrap();
*id_guard = Some(actor_id);
}
// Update max_connections if configured
// Note: We can't easily update the shared state's max_connections here
// since it's already created. For now, first handler wins.
let state = self.shared_state.clone();
let actor_id_for_closures = actor_id;
// Clone handler fields for use in listen() callback
let actor_handle_for_listen = self.actor_handle.clone();
let cancel_token_for_listen = self.cancellation_token.clone();
// Clone state and actor_id for each closure
let st_connect = state.clone();
let aid_connect = actor_id_for_closures;
let tls_for_connect = self.tls_context.clone();
let st_listen = state.clone();
let aid_listen = actor_id_for_closures;
let tls_for_listen = self.tls_context.clone();
let st_accept = state.clone();
let aid_accept = actor_id_for_closures;
let tls_for_accept = self.tls_context.clone();
let st_activate = state.clone();
let aid_activate = actor_id_for_closures;
let st_set_active = state.clone();
let aid_set_active = actor_id_for_closures;
let actor_handle_for_set_active = self.actor_handle.clone();
let cancel_token_for_set_active = self.cancellation_token.clone();
let st_transfer = state.clone();
let aid_transfer = actor_id_for_closures;
let st_peer = state.clone();
let aid_peer = actor_id_for_closures;
let st_send = state.clone();
let aid_send = actor_id_for_closures;
let st_receive = state.clone();
let aid_receive = actor_id_for_closures;
let cancel_token_for_receive = self.cancellation_token.clone();
let st_close = state.clone();
let aid_close = actor_id_for_closures;
let st_upgrade_server = state.clone();
let aid_upgrade_server = actor_id_for_closures;
let tls_for_upgrade_server = self.tls_context.clone();
let st_upgrade_client = state.clone();
let aid_upgrade_client = actor_id_for_closures;
let tls_for_upgrade_client = self.tls_context.clone();
let st_close_listener = state.clone();
let aid_close_listener = actor_id_for_closures;
builder
.interface("theater:simple/tcp")?
// ----------------------------------------------------------------
// connect(address: string) -> result<string, string>
// Outbound connections are immediately active
// ----------------------------------------------------------------
.func_async_result(
"connect",
move |_ctx: AsyncCtx<ActorStore>, input: Value| {
let st = st_connect.clone();
let actor_id = aid_connect;
let tls_ctx = tls_for_connect.clone();
async move {
let address = parse_string(&input)?;
st.check_connection_limit().await?;
debug!("tcp connect to {}", address);
let tcp_stream = TcpStream::connect(&address)
.await
.map_err(|e| Value::String(e.to_string()))?;
let peer_addr = tcp_stream
.peer_addr()
.map_err(|e| Value::String(e.to_string()))?;
// Apply TLS if configured
let unified_stream = if let Some(ref ctx) = *tls_ctx {
if let Some(ref connector) = ctx.client_connector {
// Extract hostname from address for SNI
let server_name = tls::parse_server_name(
address.split(':').next().unwrap_or(&address),
)
.map_err(|e| Value::String(e.to_string()))?;
debug!("tcp connect: performing TLS handshake with SNI {:?}", server_name);
let tls_stream = connector
.connect(server_name, tcp_stream)
.await
.map_err(|e| Value::String(format!("TLS handshake failed: {}", e)))?;
info!("tcp connect: TLS handshake complete");
UnifiedStream::ClientTls(tls_stream)
} else {
UnifiedStream::Plain(tcp_stream)
}
} else {
UnifiedStream::Plain(tcp_stream)
};
let id = st.next_id();
st.connections.lock().await.insert(
id,
ConnectionEntry {
stream: Arc::new(Mutex::new(StreamState::Full(Box::new(
unified_stream,
)))),
peer_addr,
owner: actor_id,
state: ConnectionState::Active, // Outbound = active
data_mode: DataMode::Passive,
},
);
debug!("tcp connected to {} as conn={}", address, id);
Ok::<Value, Value>(Value::String(id_to_string(id)))
}
},
)?
// ----------------------------------------------------------------
// listen(address: string) -> result<string, string>
// Binds a listener and spawns a background accept loop
// ----------------------------------------------------------------
.func_async_result(
"listen",
move |_ctx: AsyncCtx<ActorStore>, input: Value| {
let st = st_listen.clone();
let actor_id = aid_listen;
let actor_handle_arc = actor_handle_for_listen.clone();
let cancel_token = cancel_token_for_listen.clone();
let tls_ctx = tls_for_listen.clone();
async move {
let address = parse_string(&input)?;
debug!("tcp listen on {}", address);
let listener = TcpListener::bind(&address)
.await
.map_err(|e| Value::String(e.to_string()))?;
let listener_id = st.next_id();
let has_tls = match tls_ctx.as_ref() {
Some(ctx) => ctx.server_acceptor.is_some(),
None => false,
};
info!(
"tcp listening on {} as listener={} (tls={})",
address, listener_id, has_tls
);
// Take the actor_handle for use in the accept loop
let actor_handle = {
let guard = actor_handle_arc.lock().unwrap();
guard.clone()
};
let Some(actor_handle) = actor_handle else {
return Err(Value::String(
"Actor handle not available - setup() not called?".to_string(),
));
};
// Clone state for the background task
let st_for_task = st.clone();
let actor_id_for_task = actor_id;
// Spawn background accept loop with cancellation support
tokio::spawn(async move {
info!("TCP accept loop started for listener={}", listener_id);
loop {
tokio::select! {
_ = cancel_token.cancelled() => {
info!("TCP accept loop cancelled for listener={}", listener_id);
break;
}
result = listener.accept() => {
match result {
Ok((tcp_stream, peer_addr)) => {
let conn_id = st_for_task.next_id();
info!(
"tcp accepted conn={} from {} on listener={}",
conn_id, peer_addr, listener_id
);
// Apply TLS if configured
let unified_stream = if let Some(ref ctx) = *tls_ctx {
if let Some(ref acceptor) = ctx.server_acceptor {
debug!("tcp accept: performing TLS handshake for conn={}", conn_id);
match acceptor.accept(tcp_stream).await {
Ok(tls_stream) => {
info!("tcp accept: TLS handshake complete for conn={}", conn_id);
UnifiedStream::ServerTls(tls_stream)
}
Err(e) => {
error!("TLS handshake failed for conn={}: {}", conn_id, e);
continue; // Skip this connection
}
}
} else {
UnifiedStream::Plain(tcp_stream)
}
} else {
UnifiedStream::Plain(tcp_stream)
};
// Store connection in PENDING state
st_for_task.connections.lock().await.insert(
conn_id,
ConnectionEntry {
stream: Arc::new(Mutex::new(
StreamState::Full(Box::new(unified_stream)),
)),
peer_addr,
owner: actor_id_for_task,
state: ConnectionState::Pending,
data_mode: DataMode::Passive,
},
);
// Call the actor's handle-connection export
let conn_id_str = id_to_string(conn_id);
let params =
Value::Tuple(vec![Value::String(conn_id_str)]);
if let Err(e) = actor_handle
.call_function(
"theater:simple/tcp-client.handle-connection"
.to_string(),
params,
)
.await
{
error!(
"Failed to call handle-connection for conn={}: {}",
conn_id, e
);
// Clean up the pending connection
st_for_task.connections.lock().await.remove(&conn_id);
}
}
Err(e) => {
error!(
"TCP accept error on listener={}: {}",
listener_id, e
);
}
}
}
}
}
info!("TCP accept loop stopped for listener={}", listener_id);
});
Ok::<Value, Value>(Value::String(id_to_string(listener_id)))
}
},
)?
// ----------------------------------------------------------------
// accept(listener-id: string) -> result<string, string>
// Manual accept - returns connection in PENDING state
// ----------------------------------------------------------------
.func_async_result(
"accept",
move |_ctx: AsyncCtx<ActorStore>, input: Value| {
let st = st_accept.clone();
let actor_id = aid_accept;
let tls_ctx = tls_for_accept.clone();
async move {
let listener_id_str = parse_string(&input)?;
let listener_id = string_to_id(&listener_id_str)?;
debug!("tcp accept on listener={}", listener_id);
// Check ownership
let mut listeners = st.listeners.lock().await;
let entry = listeners.get_mut(&listener_id).ok_or_else(|| {
Value::String(format!("Listener not found: {}", listener_id_str))
})?;
if entry.owner != actor_id {
return Err(Value::String(format!(
"Listener {} not owned by this actor",
listener_id_str
)));
}
let (tcp_stream, peer_addr) = entry
.listener
.accept()
.await
.map_err(|e| Value::String(e.to_string()))?;
let conn_id = st.next_id();
drop(listeners); // Release lock before acquiring connections lock
// Apply TLS if configured
let unified_stream = if let Some(ref ctx) = *tls_ctx {
if let Some(ref acceptor) = ctx.server_acceptor {
debug!("tcp manual accept: performing TLS handshake for conn={}", conn_id);
let tls_stream = acceptor
.accept(tcp_stream)
.await
.map_err(|e| Value::String(format!("TLS handshake failed: {}", e)))?;
info!("tcp manual accept: TLS handshake complete for conn={}", conn_id);
UnifiedStream::ServerTls(tls_stream)
} else {
UnifiedStream::Plain(tcp_stream)
}
} else {
UnifiedStream::Plain(tcp_stream)
};
st.connections.lock().await.insert(
conn_id,
ConnectionEntry {
stream: Arc::new(Mutex::new(StreamState::Full(Box::new(
unified_stream,
)))),
peer_addr,
owner: actor_id,
state: ConnectionState::Pending, // Starts pending!
data_mode: DataMode::Passive,
},
);
debug!("tcp accepted conn={} from {} (pending)", conn_id, peer_addr);
Ok::<Value, Value>(Value::String(id_to_string(conn_id)))
}
},
)?
// ----------------------------------------------------------------
// activate(connection-id: string) -> result<_, string>
// Activate a pending connection for this actor
// ----------------------------------------------------------------
.func_async_result(
"activate",
move |_ctx: AsyncCtx<ActorStore>, input: Value| {
let st = st_activate.clone();
let actor_id = aid_activate;
async move {
let conn_id_str = parse_string(&input)?;
let conn_id = string_to_id(&conn_id_str)?;
let mut connections = st.connections.lock().await;
let entry = connections.get_mut(&conn_id).ok_or_else(|| {
Value::String(format!("Connection not found: {}", conn_id_str))
})?;
if entry.owner != actor_id {
return Err(Value::String(format!(
"Connection {} not owned by this actor",
conn_id_str
)));
}
if entry.state == ConnectionState::Active {
return Err(Value::String(format!(
"Connection {} is already active",
conn_id_str
)));
}
entry.state = ConnectionState::Active;
debug!("tcp activated conn={}", conn_id);
Ok::<Value, Value>(Value::Tuple(vec![]))
}
},
)?
// ----------------------------------------------------------------
// set-active(connection-id: string, mode: string) -> result<_, string>
// Set data mode: "passive", "active", or "once"
// ----------------------------------------------------------------
.func_async_result(
"set-active",
move |_ctx: AsyncCtx<ActorStore>, input: Value| {
let st = st_set_active.clone();
let actor_id = aid_set_active;
let actor_handle_arc = actor_handle_for_set_active.clone();
let cancel_token = cancel_token_for_set_active.clone();
async move {
let (conn_id_str, mode_str) = parse_two_strings(&input)?;
let conn_id = string_to_id(&conn_id_str)?;
let new_mode = match mode_str.as_str() {
"passive" => DataMode::Passive,
"active" => DataMode::Active,
"once" => DataMode::Once,
_ => {
return Err(Value::String(format!(
"Invalid mode '{}': expected 'passive', 'active', or 'once'",
mode_str
)));
}
};
let mut connections = st.connections.lock().await;
let entry = connections.get_mut(&conn_id).ok_or_else(|| {
Value::String(format!("Connection not found: {}", conn_id_str))
})?;
if entry.owner != actor_id {
return Err(Value::String(format!(
"Connection {} not owned by this actor",
conn_id_str
)));
}
if entry.state != ConnectionState::Active {
return Err(Value::String(format!(
"Connection {} must be activated before setting data mode",
conn_id_str
)));
}
let old_mode = entry.data_mode;
// Handle mode transitions
match (old_mode, new_mode) {
(DataMode::Passive, DataMode::Active | DataMode::Once) => {
// Transitioning to active/once mode - split stream and spawn reader
let mut stream_guard = entry.stream.lock().await;
let stream = std::mem::replace(&mut *stream_guard, StreamState::Closed);
let full_stream = match stream {
StreamState::Full(s) => s,
other @ StreamState::WriteOnly(_) => {
// Restore — we replaced with Closed above.
*stream_guard = other;
return Err(Value::String(format!(
"Connection {} is already in active mode",
conn_id_str
)));
}
StreamState::Closed => {
return Err(Value::String(format!(
"Connection {} is closed",
conn_id_str
)));
}
};
let (read_half, write_half) = full_stream.into_split();
*stream_guard = StreamState::WriteOnly(write_half);
drop(stream_guard);
entry.data_mode = new_mode;
// Get actor handle for callbacks
let actor_handle = {
let guard = actor_handle_arc.lock().unwrap();
guard.clone()
};
let Some(actor_handle) = actor_handle else {
return Err(Value::String(
"Actor handle not available".to_string(),
));
};
// Spawn background read task with cancellation support
let conn_id_for_task = conn_id;
let st_for_task = st.clone();
let is_once = new_mode == DataMode::Once;
let cancel_token_for_task = cancel_token.clone();
tokio::spawn(async move {
tcp_read_loop(
conn_id_for_task,
read_half,
actor_handle,
st_for_task,
is_once,
cancel_token_for_task,
)
.await;
});
info!(
"tcp conn={} set to {} mode, read loop spawned",
conn_id, mode_str
);
}
(DataMode::Active | DataMode::Once, DataMode::Passive) => {
// Can't go back to passive once in active mode (stream is split)
return Err(Value::String(format!(
"Cannot switch connection {} back to passive mode (stream is split)",
conn_id_str
)));
}
(DataMode::Active, DataMode::Once) | (DataMode::Once, DataMode::Active) => {
// Can't switch between active and once (would need to stop/restart reader)
return Err(Value::String(format!(
"Cannot switch connection {} between active and once modes",
conn_id_str
)));
}
_ => {
// Same mode, no-op
debug!("tcp conn={} already in {} mode", conn_id, mode_str);
}
}
Ok::<Value, Value>(Value::Tuple(vec![]))
}
},
)?
// ----------------------------------------------------------------
// transfer(connection-id: string, target-actor: string) -> result<_, string>
// Transfer connection to another actor (and activate it)
// ----------------------------------------------------------------
.func_async_result(
"transfer",
move |ctx: AsyncCtx<ActorStore>, input: Value| {
let st = st_transfer.clone();
let actor_id = aid_transfer;
async move {
let (conn_id_str, target_actor_str) = parse_two_strings(&input)?;
let conn_id = string_to_id(&conn_id_str)?;
let target_actor: TheaterId = target_actor_str
.parse()
.map_err(|e| Value::String(format!("Invalid actor ID: {}", e)))?;
{
let mut connections = st.connections.lock().await;
let entry = connections.get_mut(&conn_id).ok_or_else(|| {
Value::String(format!("Connection not found: {}", conn_id_str))
})?;
if entry.owner != actor_id {
return Err(Value::String(format!(
"Connection {} not owned by this actor",
conn_id_str
)));
}
// Transfer ownership and activate
let old_owner = entry.owner;
entry.owner = target_actor;
entry.state = ConnectionState::Active;
info!(
"tcp transferred conn={} from {} to {} (now active)",
conn_id, old_owner, target_actor
);
}
// Get target actor's handle and call handle-connection-transfer
let store = ctx.data();
let theater_tx = store.theater_tx.clone();
let (handle_tx, handle_rx) = tokio::sync::oneshot::channel();
let get_handle_cmd = theater::messages::TheaterCommand::GetActorHandle {
actor_id: target_actor,
response_tx: handle_tx,
};
theater_tx.send(get_handle_cmd).await
.map_err(|e| Value::String(format!("Failed to get target handle: {}", e)))?;
let target_handle = match handle_rx.await {
Ok(Some(handle)) => handle,
Ok(None) => return Err(Value::String("Target actor handle not found".to_string())),
Err(e) => return Err(Value::String(format!("Failed to receive handle: {}", e))),
};
// Call handle-connection-transfer on target
// Just pass conn_id - runtime will prepend state to make (state, conn_id)
let params = Value::String(conn_id_str.clone());
if let Err(e) = target_handle
.call_function(
"theater:simple/tcp-client.handle-connection-transfer".to_string(),
params,
)
.await
{
warn!("Failed to call handle-connection-transfer: {:?}", e);
// Don't fail the transfer, just log the warning
}
Ok::<Value, Value>(Value::Tuple(vec![]))
}
},
)?
// ----------------------------------------------------------------
// peer-address(connection-id: string) -> result<string, string>
// Get peer address (works in pending or active state)
// ----------------------------------------------------------------
.func_async_result(
"peer-address",
move |_ctx: AsyncCtx<ActorStore>, input: Value| {
let st = st_peer.clone();
let actor_id = aid_peer;
async move {
let conn_id_str = parse_string(&input)?;
let conn_id = string_to_id(&conn_id_str)?;
let connections = st.connections.lock().await;
let entry = connections.get(&conn_id).ok_or_else(|| {
Value::String(format!("Connection not found: {}", conn_id_str))
})?;
if entry.owner != actor_id {
return Err(Value::String(format!(
"Connection {} not owned by this actor",
conn_id_str
)));
}
Ok::<Value, Value>(Value::String(entry.peer_addr.to_string()))
}
},
)?
// ----------------------------------------------------------------
// send(connection-id: string, data: list<u8>) -> result<u64, string>
// ----------------------------------------------------------------
.func_async_result(
"send",
move |_ctx: AsyncCtx<ActorStore>, input: Value| {
let st = st_send.clone();
let actor_id = aid_send;
async move {
let (conn_id_str, data) = parse_string_and_bytes(&input)?;
let conn_id = string_to_id(&conn_id_str)?;
let len = data.len();
// Lock the outer map only long enough to validate metadata
// and clone the per-connection stream Arc. The actual I/O
// runs without holding the outer lock — that lets two
// actors do I/O on different connections in parallel.
let stream_arc = {
let connections = st.connections.lock().await;
let entry = connections.get(&conn_id).ok_or_else(|| {
Value::String(format!("Connection not found: {}", conn_id_str))
})?;
if entry.owner != actor_id {
return Err(Value::String(format!(
"Connection {} not owned by this actor",
conn_id_str
)));
}
if entry.state == ConnectionState::Pending {
return Err(Value::String(format!(
"Connection {} is pending - call activate() or transfer() first",
conn_id_str
)));
}
entry.stream.clone()
};
let mut stream_guard = stream_arc.lock().await;
match &mut *stream_guard {
StreamState::Full(stream) => {
stream
.write_all(&data)
.await
.map_err(|e| Value::String(e.to_string()))?;
}
StreamState::WriteOnly(write_half) => {
write_half
.write_all(&data)
.await
.map_err(|e| Value::String(e.to_string()))?;
}
StreamState::Closed => {
return Err(Value::String(format!(
"Connection {} is closed",
conn_id_str
)));
}
}
debug!("tcp send conn={} {} bytes", conn_id, len);
Ok::<Value, Value>(Value::U64(len as u64))
}
},
)?
// ----------------------------------------------------------------
// receive(connection-id: string, max-bytes: u32) -> result<list<u8>, string>
// ----------------------------------------------------------------
.func_async_result(
"receive",
move |_ctx: AsyncCtx<ActorStore>, input: Value| {
let st = st_receive.clone();
let actor_id = aid_receive;
let cancel_token = cancel_token_for_receive.clone();
async move {
let (conn_id_str, max_bytes) = parse_string_and_u32(&input)?;
let conn_id = string_to_id(&conn_id_str)?;
// Lock the outer map only long enough to validate metadata
// and clone the per-connection stream Arc. The actual read
// runs without holding the outer lock so other actors can
// do their own I/O concurrently on other connections.
let stream_arc = {
let connections = st.connections.lock().await;
let entry = connections.get(&conn_id).ok_or_else(|| {
Value::String(format!("Connection not found: {}", conn_id_str))
})?;
if entry.owner != actor_id {
return Err(Value::String(format!(
"Connection {} not owned by this actor",
conn_id_str
)));
}
if entry.state == ConnectionState::Pending {
return Err(Value::String(format!(
"Connection {} is pending - call activate() or transfer() first",
conn_id_str
)));
}
if entry.data_mode != DataMode::Passive {
return Err(Value::String(format!(
"Connection {} is in active mode - data is pushed via on-data callback",
conn_id_str
)));
}
entry.stream.clone()
};
let mut stream_guard = stream_arc.lock().await;
let stream = match &mut *stream_guard {
StreamState::Full(stream) => stream,
StreamState::WriteOnly(_) => {
return Err(Value::String(format!(
"Connection {} read half not available (in active mode)",
conn_id_str
)));
}
StreamState::Closed => {
return Err(Value::String(format!(
"Connection {} is closed",
conn_id_str
)));
}
};
let mut buf = vec![0u8; max_bytes as usize];
// Use select to make the read interruptible on shutdown
let n = tokio::select! {
result = stream.read(&mut buf) => {
result.map_err(|e| Value::String(e.to_string()))?
}
_ = cancel_token.cancelled() => {
info!("TCP receive cancelled due to shutdown, conn={}", conn_id);
return Err(Value::String("Connection closed: actor shutting down".to_string()));
}
};
debug!(
"tcp receive conn={} {} bytes (max={})",
conn_id, n, max_bytes
);
buf.truncate(n);
Ok::<Value, Value>(Value::List {
elem_type: ValueType::U8,
items: buf.into_iter().map(Value::U8).collect(),
})
}
},
)?
// ----------------------------------------------------------------
// close(connection-id: string) -> result<_, string>
//
// Gracefully shuts the write side of the stream before dropping —
// for TLS streams this sends the close_notify alert so strict
// clients (e.g. rustls) don't see an "unexpected EOF". Plain TCP
// streams get a normal FIN.
// ----------------------------------------------------------------
.func_async_result(
"close",
move |_ctx: AsyncCtx<ActorStore>, input: Value| {
let st = st_close.clone();
let actor_id = aid_close;
async move {
let conn_id_str = parse_string(&input)?;
let conn_id = string_to_id(&conn_id_str)?;
// Take the stream out of the map first, holding the
// outer lock only long enough to validate ownership
// and remove the entry.
let stream_arc = {
let mut connections = st.connections.lock().await;
let entry = connections.get(&conn_id).ok_or_else(|| {
Value::String(format!("Connection not found: {}", conn_id_str))
})?;
if entry.owner != actor_id {
return Err(Value::String(format!(
"Connection {} not owned by this actor",
conn_id_str
)));
}
let arc = entry.stream.clone();
connections.remove(&conn_id);
arc
};
// Move the stream out and call shutdown on the write
// side. Errors are non-fatal — peer may already have
// closed.
let mut guard = stream_arc.lock().await;
let taken = std::mem::replace(&mut *guard, StreamState::Closed);
drop(guard);
match taken {
StreamState::Full(mut s) => {
let _ = AsyncWriteExt::shutdown(&mut *s).await;
}
StreamState::WriteOnly(mut w) => {
let _ = AsyncWriteExt::shutdown(&mut w).await;
}
StreamState::Closed => {}
}
debug!("tcp close conn={} (graceful)", conn_id);
Ok::<Value, Value>(Value::Tuple(vec![]))
}
},
)?
// ----------------------------------------------------------------
// upgrade-to-tls-server(connection-id: string) -> result<_, string>
//
// For STARTTLS-style protocols: the actor accepts a plain TCP
// connection, exchanges a few protocol lines, then calls this to
// wrap the existing stream with TLS using the server_tls cert
// configured on this handler. After this returns Ok, the same
// connection-id transports TLS-encrypted bytes.
// ----------------------------------------------------------------
.func_async_result(
"upgrade-to-tls-server",
move |_ctx: AsyncCtx<ActorStore>, input: Value| {
let st = st_upgrade_server.clone();
let actor_id = aid_upgrade_server;
let tls_ctx = tls_for_upgrade_server.clone();
async move {
let conn_id_str = parse_string(&input)?;
let conn_id = string_to_id(&conn_id_str)?;
let acceptor = match tls_ctx.as_ref() {
Some(ctx) => match &ctx.server_acceptor {
Some(a) => a.clone(),
None => {
return Err(Value::String(
"server_tls not configured on this handler".into(),
))
}
},
None => {
return Err(Value::String(
"server_tls not configured on this handler".into(),
))
}
};
let stream_arc = {
let connections = st.connections.lock().await;
let entry = connections.get(&conn_id).ok_or_else(|| {
Value::String(format!("Connection not found: {}", conn_id_str))
})?;
if entry.owner != actor_id {
return Err(Value::String(format!(
"Connection {} not owned by this actor",
conn_id_str
)));
}
if entry.state != ConnectionState::Active {
return Err(Value::String(format!(
"Connection {} must be activated before TLS upgrade",
conn_id_str
)));
}
if entry.data_mode != DataMode::Passive {
return Err(Value::String(format!(
"Connection {} must be in passive mode for TLS upgrade",
conn_id_str
)));
}
entry.stream.clone()
};
let mut guard = stream_arc.lock().await;
let taken = std::mem::replace(&mut *guard, StreamState::Closed);
let inner = match taken {
StreamState::Full(boxed) => *boxed,
StreamState::WriteOnly(w) => {
*guard = StreamState::WriteOnly(w);
return Err(Value::String(format!(
"Connection {} is split; TLS upgrade not supported",
conn_id_str
)));
}
StreamState::Closed => {
return Err(Value::String(format!(
"Connection {} is closed",
conn_id_str
)));
}
};
let tcp = match inner {
UnifiedStream::Plain(tcp) => tcp,
other => {
*guard = StreamState::Full(Box::new(other));
return Err(Value::String(format!(
"Connection {} is already TLS",
conn_id_str
)));
}
};
let tls_stream = match acceptor.accept(tcp).await {
Ok(s) => s,
Err(e) => {
// Stream is gone — leave entry as Closed.
return Err(Value::String(format!(
"TLS server handshake failed: {}",
e
)));
}
};
*guard = StreamState::Full(Box::new(UnifiedStream::ServerTls(tls_stream)));
drop(guard);
debug!("tcp upgrade-to-tls-server conn={}", conn_id);
Ok::<Value, Value>(Value::Tuple(vec![]))
}
},
)?
// ----------------------------------------------------------------
// upgrade-to-tls-client(connection-id, server-name) -> result<_, string>
//
// The client-side mirror of upgrade-to-tls-server: wraps an
// existing plain TCP connection with TLS using the client_tls
// config. server-name is used for SNI and cert verification.
// ----------------------------------------------------------------
.func_async_result(
"upgrade-to-tls-client",
move |_ctx: AsyncCtx<ActorStore>, input: Value| {
let st = st_upgrade_client.clone();
let actor_id = aid_upgrade_client;
let tls_ctx = tls_for_upgrade_client.clone();
async move {
let (conn_id_str, server_name_str) = parse_two_strings(&input)?;
let conn_id = string_to_id(&conn_id_str)?;
let connector = match tls_ctx.as_ref() {
Some(ctx) => match &ctx.client_connector {
Some(c) => c.clone(),
None => {
return Err(Value::String(
"client_tls not configured on this handler".into(),
))
}
},
None => {
return Err(Value::String(
"client_tls not configured on this handler".into(),
))
}
};
let server_name =
rustls::pki_types::ServerName::try_from(server_name_str.clone())
.map_err(|e| {
Value::String(format!(
"Invalid server name {:?}: {}",
server_name_str, e
))
})?;
let stream_arc = {
let connections = st.connections.lock().await;
let entry = connections.get(&conn_id).ok_or_else(|| {
Value::String(format!("Connection not found: {}", conn_id_str))
})?;
if entry.owner != actor_id {
return Err(Value::String(format!(
"Connection {} not owned by this actor",
conn_id_str
)));
}
if entry.state != ConnectionState::Active {
return Err(Value::String(format!(
"Connection {} must be activated before TLS upgrade",
conn_id_str
)));
}
if entry.data_mode != DataMode::Passive {
return Err(Value::String(format!(
"Connection {} must be in passive mode for TLS upgrade",
conn_id_str
)));
}
entry.stream.clone()
};
let mut guard = stream_arc.lock().await;
let taken = std::mem::replace(&mut *guard, StreamState::Closed);
let inner = match taken {
StreamState::Full(boxed) => *boxed,
StreamState::WriteOnly(w) => {
*guard = StreamState::WriteOnly(w);
return Err(Value::String(format!(
"Connection {} is split; TLS upgrade not supported",
conn_id_str
)));
}
StreamState::Closed => {
return Err(Value::String(format!(
"Connection {} is closed",
conn_id_str
)));
}
};
let tcp = match inner {
UnifiedStream::Plain(tcp) => tcp,
other => {
*guard = StreamState::Full(Box::new(other));
return Err(Value::String(format!(
"Connection {} is already TLS",
conn_id_str
)));
}
};
let tls_stream = match connector.connect(server_name, tcp).await {
Ok(s) => s,
Err(e) => {
return Err(Value::String(format!(
"TLS client handshake failed: {}",
e
)));
}
};
*guard = StreamState::Full(Box::new(UnifiedStream::ClientTls(tls_stream)));
drop(guard);
debug!(
"tcp upgrade-to-tls-client conn={} server_name={}",
conn_id, server_name_str
);
Ok::<Value, Value>(Value::Tuple(vec![]))
}
},
)?
// ----------------------------------------------------------------
// close-listener(listener-id: string) -> result<_, string>
// ----------------------------------------------------------------
.func_async_result(
"close-listener",
move |_ctx: AsyncCtx<ActorStore>, input: Value| {
let st = st_close_listener.clone();
let actor_id = aid_close_listener;
async move {
let listener_id_str = parse_string(&input)?;
let listener_id = string_to_id(&listener_id_str)?;
let mut listeners = st.listeners.lock().await;
let entry = listeners.get(&listener_id).ok_or_else(|| {
Value::String(format!("Listener not found: {}", listener_id_str))
})?;
if entry.owner != actor_id {
return Err(Value::String(format!(
"Listener {} not owned by this actor",
listener_id_str
)));
}
listeners.remove(&listener_id);
debug!("tcp close listener={}", listener_id);
Ok::<Value, Value>(Value::Tuple(vec![]))
}
},
)?;
ctx.mark_satisfied("theater:simple/tcp");
info!("TCP host functions (Pack) set up successfully");
Ok(())
}
fn supports_composite(&self) -> bool {
true
}
}
// ============================================================================
// Active Mode Read Loop
// ============================================================================
/// Buffer size for active mode reads
const ACTIVE_READ_BUFFER_SIZE: usize = 8192;
/// Background task that reads from a connection and calls on-data/on-close callbacks.
///
/// This is spawned when a connection enters "active" or "once" mode.
async fn tcp_read_loop(
conn_id: u64,
mut read_half: UnifiedReadHalf,
actor_handle: ActorHandle,
shared_state: Arc<SharedTcpState>,
is_once: bool,
cancel_token: CancellationToken,
) {
let conn_id_str = id_to_string(conn_id);
info!(
"tcp read loop started for conn={} (once={})",
conn_id, is_once
);
let mut buf = vec![0u8; ACTIVE_READ_BUFFER_SIZE];
loop {
tokio::select! {
_ = cancel_token.cancelled() => {
info!("tcp read loop cancelled for conn={}", conn_id);
// Remove connection from shared state
shared_state.connections.lock().await.remove(&conn_id);
break;
}
result = read_half.read(&mut buf) => {
match result {
Ok(0) => {
// EOF - connection closed by peer
info!("tcp conn={} received EOF", conn_id);
// Call on-close callback
let params = Value::Tuple(vec![
Value::String(conn_id_str.clone()),
Value::String("eof".to_string()),
]);
if let Err(e) = actor_handle
.call_function("theater:simple/tcp-client.on-close".to_string(), params)
.await
{
warn!("tcp conn={} on-close callback failed: {}", conn_id, e);
}
// Remove connection from shared state
shared_state.connections.lock().await.remove(&conn_id);
break;
}
Ok(n) => {
// Data received - call on-data callback
let data = buf[..n].to_vec();
debug!("tcp conn={} received {} bytes, calling on-data", conn_id, n);
let params = Value::Tuple(vec![
Value::String(conn_id_str.clone()),
Value::List {
elem_type: ValueType::U8,
items: data.into_iter().map(Value::U8).collect(),
},
]);
if let Err(e) = actor_handle
.call_function("theater:simple/tcp-client.on-data".to_string(), params)
.await
{
error!("tcp conn={} on-data callback failed: {}", conn_id, e);
// Continue reading even if callback fails
}
if is_once {
// Once mode: switch back to passive after one read
info!("tcp conn={} once mode complete, switching to passive", conn_id);
// Update the connection's data mode
if let Some(entry) = shared_state.connections.lock().await.get_mut(&conn_id) {
entry.data_mode = DataMode::Passive;
}
break;
}
}
Err(e) => {
// Read error - connection broken
error!("tcp conn={} read error: {}", conn_id, e);
// Call on-close callback with error
let params = Value::Tuple(vec![
Value::String(conn_id_str.clone()),
Value::String(e.to_string()),
]);
if let Err(e) = actor_handle
.call_function("theater:simple/tcp-client.on-close".to_string(), params)
.await
{
warn!("tcp conn={} on-close callback failed: {}", conn_id, e);
}
// Remove connection from shared state
shared_state.connections.lock().await.remove(&conn_id);
break;
}
}
}
}
}
info!("tcp read loop stopped for conn={}", conn_id);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_tcp_handler_creation() {
let config = TcpHandlerConfig::default();
let handler = TcpHandler::new(config);
assert_eq!(handler.name(), "tcp");
assert_eq!(
handler.imports(),
Some(vec!["theater:simple/tcp".to_string()])
);
assert_eq!(
handler.exports(),
Some(vec!["theater:simple/tcp-client".to_string()])
);
}
#[test]
fn test_tcp_handler_clone_shares_state() {
let config = TcpHandlerConfig::default();
let handler = TcpHandler::new(config);
let cloned = handler.create_instance(None);
// Both should have the same name
assert_eq!(cloned.name(), "tcp");
// The key test: shared_state Arc should be the same
// (We can't easily test this without exposing internals, but the
// implementation clones the Arc, not the data)
}
#[test]
fn test_tcp_interface_hash_determinism() {
let interface1 = tcp_interface();
let interface2 = tcp_interface();
assert_eq!(interface1.hash(), interface2.hash());
}
#[test]
fn test_tcp_handler_interface_hashes() {
let config = TcpHandlerConfig::default();
let handler = TcpHandler::new(config);
let hashes = handler.interface_hashes();
assert_eq!(hashes.len(), 1);
assert_eq!(hashes[0].0, "theater:simple/tcp");
// Hash should be non-zero
assert!(!hashes[0].1.as_bytes().iter().all(|&b| b == 0));
}
#[test]
fn test_connection_state_enum() {
assert_ne!(ConnectionState::Pending, ConnectionState::Active);
}
#[test]
fn test_data_mode_enum() {
assert_ne!(DataMode::Passive, DataMode::Active);
assert_ne!(DataMode::Passive, DataMode::Once);
assert_ne!(DataMode::Active, DataMode::Once);
}
}