rzmq 0.5.11

High performance, fully asynchronous, safe pure-Rust implementation of ZeroMQ (ØMQ) messaging with io_uring and TCP Cork acceleration on Linux.
Documentation
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
#![cfg(feature = "io-uring")]

use super::buffer_manager::BufferRingManager;
use super::worker::InternalOpTracker;
use crate::io_uring_backend::connection_handler::{
  HandlerIoOps, HandlerSqeBlueprint, HandlerUpstreamEvent, ProtocolHandlerFactory,
  UringConnectionHandler, UringWorkerInterface, UserData, WorkerIoConfig,
};
use crate::io_uring_backend::ops::{HANDLER_INTERNAL_SEND_OP_UD, ProtocolConfig};
use crate::io_uring_backend::worker::MultishotReader;
use crate::message::{Msg, MsgFlags};
use crate::protocol::zmtp::{
  command::{ZmtpCommand, ZmtpReady},
  greeting::{GREETING_LENGTH, MECHANISM_LENGTH, ZmtpGreeting},
  manual_parser::ZmtpManualParser,
};
#[cfg(feature = "noise_xx")]
use crate::security::NoiseXxMechanism;
use crate::security::framer::{ISecureFramer, NullFramer};
use crate::security::{
  IDataCipher, Mechanism, NullMechanism, PlainMechanism, negotiate_security_mechanism,
};
use crate::socket::options::ZmtpEngineConfig;
use crate::{Blob, ZmqError};

use std::any::Any;
use std::collections::{HashMap, VecDeque};
use std::os::unix::io::RawFd;
use std::sync::Arc;
use std::time::{Duration, Instant};

use bytes::{BufMut, Bytes, BytesMut};
use dryoc::types::Bytes as DryocBytes;
use tokio_util::codec::Encoder;
use tracing::{debug, error, info, trace, warn};

const ZC_SEND_THRESHOLD: usize = 1024;

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum ZmtpHandlerPhase {
  Initial,
  ClientSendGreeting,
  ClientWaitServerGreeting,
  ServerWaitClientGreeting,
  ServerSendGreeting,
  SecurityExchange,
  ReadyClientSend,
  ReadyClientWaitServer,
  ReadyServerWaitClient,
  ReadyServerSend,
  DataPhase,
  Error,
  Closing,
  Closed,
}

pub struct ZmtpUringHandler {
  fd: RawFd,
  zmtp_config: Arc<ZmtpEngineConfig>,
  is_server: bool,
  phase: ZmtpHandlerPhase,

  greeting_buffer: BytesMut,
  network_read_accumulator: BytesMut,

  security_mechanism: Option<Box<dyn Mechanism>>,
  framer: Box<dyn ISecureFramer>,

  last_activity_time: Instant,
  last_ping_sent_time: Option<Instant>,
  waiting_for_pong: bool,
  heartbeat_ivl: Option<Duration>,
  heartbeat_timeout_duration: Duration,

  outgoing_app_messages: VecDeque<(Msg, UserData)>,
  outgoing_multipart_app_messages: VecDeque<(Vec<Msg>, UserData)>,

  handshake_timeout: Duration,
  handshake_timeout_deadline: Instant,

  peer_identity_from_security: Option<Blob>,
  peer_identity_from_ready: Option<Blob>,
  final_peer_identity: Option<Blob>,

  last_sent_was_ping: bool,
  multishot_reader: Option<MultishotReader>,
}

impl ZmtpUringHandler {
  pub fn new(fd: RawFd, zmtp_config_arg: Arc<ZmtpEngineConfig>, is_server: bool) -> Self {
    let handshake_timeout_duration = zmtp_config_arg
      .handshake_timeout
      .unwrap_or(Duration::from_secs(30));
    let heartbeat_timeout_val = zmtp_config_arg.heartbeat_timeout.unwrap_or_else(|| {
      zmtp_config_arg
        .heartbeat_ivl
        .map_or(Duration::from_secs(30), |ivl| ivl.saturating_mul(2))
    });
    let heartbeat_ivl_val = zmtp_config_arg.heartbeat_ivl;

    Self {
      fd,
      zmtp_config: zmtp_config_arg,
      is_server,
      phase: ZmtpHandlerPhase::Initial,
      greeting_buffer: BytesMut::with_capacity(GREETING_LENGTH),
      network_read_accumulator: BytesMut::with_capacity(8192 * 2),
      security_mechanism: None,
      framer: Box::new(NullFramer::new()),
      last_activity_time: Instant::now(),
      last_ping_sent_time: None,
      waiting_for_pong: false,
      heartbeat_ivl: heartbeat_ivl_val,
      heartbeat_timeout_duration: heartbeat_timeout_val,
      outgoing_app_messages: VecDeque::new(),
      outgoing_multipart_app_messages: VecDeque::new(),
      handshake_timeout: handshake_timeout_duration,
      handshake_timeout_deadline: Instant::now() + handshake_timeout_duration,
      peer_identity_from_security: None,
      peer_identity_from_ready: None,
      final_peer_identity: None,
      last_sent_was_ping: false,
      multishot_reader: None,
    }
  }

  fn transition_to_error(
    &mut self,
    ops: &mut HandlerIoOps,
    error: ZmqError,
    interface: &UringWorkerInterface<'_>,
  ) {
    if self.phase == ZmtpHandlerPhase::Error || self.phase == ZmtpHandlerPhase::Closed {
      return;
    }
    let previous_phase = self.phase;
    error!(fd = self.fd, error_msg = %error, ?previous_phase, "ZmtpUringHandler: Transitioning to error state.");
    self.phase = ZmtpHandlerPhase::Error;

    ops.initiate_close_due_to_error = true;
    if !ops
      .sqe_blueprints
      .iter()
      .any(|bp| matches!(bp, HandlerSqeBlueprint::RequestClose))
    {
      ops.sqe_blueprints.push(HandlerSqeBlueprint::RequestClose);
    }

    // Signal error upstream using the new HandlerUpstreamEvent
    if !matches!(
      previous_phase,
      ZmtpHandlerPhase::DataPhase | ZmtpHandlerPhase::Error | ZmtpHandlerPhase::Closed
    ) {
      warn!(
        fd = self.fd,
        "Signaling handshake failure upstream due to error: {}", error
      );
      let _ = interface
        .worker_io_config
        .upstream_event_tx
        .try_send((self.fd, HandlerUpstreamEvent::Error(error)));
    }
  }

  fn build_ready_properties(&self) -> HashMap<String, Vec<u8>> {
    let mut props = HashMap::new();
    props.insert(
      "Socket-Type".to_string(),
      self.zmtp_config.socket_type_name.as_bytes().to_vec(),
    );
    if let Some(id_blob) = &self.zmtp_config.routing_id {
      if !id_blob.is_empty() && id_blob.len() <= 255 {
        props.insert("Identity".to_string(), id_blob.to_vec());
      } else if id_blob.is_empty() {
        trace!(
          fd = self.fd,
          "Local routing_id is empty, not sending in READY."
        );
      } else {
        warn!(
          fd = self.fd,
          id_len = id_blob.len(),
          "Local routing_id too long (max 255), not sending in READY."
        );
      }
    }
    props
  }

  fn signal_upstream_handshake_complete(
    &mut self,
    interface: &UringWorkerInterface<'_>,
  ) -> Result<(), ZmqError> {
    self.final_peer_identity = self
      .peer_identity_from_ready
      .clone()
      .or_else(|| self.peer_identity_from_security.clone());

    info!(fd=self.fd, final_peer_id=?self.final_peer_identity, "ZmtpUringHandler: Signaling ZMTP handshake completion upstream.");

    // Use the new HandlerUpstreamEvent to signal completion
    let event = HandlerUpstreamEvent::HandshakeComplete {
      peer_identity: self.final_peer_identity.clone(),
    };

    interface
      .worker_io_config
      .upstream_event_tx
      .try_send((self.fd, event))
      .map_err(|e| {
        error!(
          fd = self.fd,
          "Failed to send HandshakeComplete signal upstream: {:?}", e
        );
        ZmqError::Internal("Failed to signal handshake completion".into())
      })
      .map(|_| ())
  }

  fn process_buffered_reads(
    &mut self,
    interface: &UringWorkerInterface<'_>,
    ops: &mut HandlerIoOps,
  ) -> Result<bool, ZmqError> {
    let mut made_progress_this_call = false;

    // Outer loop: keep processing as long as progress is made or phases change
    // and buffers might have data relevant to the new phase.
    'phase_processing_loop: loop {
      // Store initial buffer lengths to detect if any data was consumed in this iteration of the outer loop.
      // This helps decide if we should loop again or if we're stuck.
      let initial_greeting_len_outer = self.greeting_buffer.len();
      let initial_network_acc_len_outer = self.network_read_accumulator.len();

      // Removed: plaintext_zmtp_frame_accumulator length check (buffer removed)

      let mut progress_this_iteration = false;

      // Handshake timeout check
      if Instant::now() > self.handshake_timeout_deadline
        && !matches!(
          self.phase,
          ZmtpHandlerPhase::DataPhase | ZmtpHandlerPhase::Error | ZmtpHandlerPhase::Closed
        )
      {
        warn!(fd=self.fd, current_phase=?self.phase, "Overall handshake timeout occurred in process_buffered_reads.");
        let err = ZmqError::Timeout;
        // transition_to_error will modify ops and self.phase
        self.transition_to_error(ops, err.clone(), interface);
        return Err(err);
      }

      trace!(fd=self.fd, phase=?self.phase, greeting_buf_len=self.greeting_buffer.len(), net_acc_len=self.network_read_accumulator.len(), "ProcessBufferedReads: Top of loop");

      match self.phase {
        ZmtpHandlerPhase::Initial => {
          error!(
            fd = self.fd,
            "ZmtpHandler in Initial phase during process_buffered_reads. This is a bug."
          );
          let err =
            ZmqError::InvalidState("ZmtpHandler in Initial phase during data processing".into());
          self.transition_to_error(ops, err.clone(), interface);
          return Err(err);
        }

        // Phases where this function primarily waits for send completions, not for processing read data.
        ZmtpHandlerPhase::ClientSendGreeting
        | ZmtpHandlerPhase::ServerSendGreeting
        | ZmtpHandlerPhase::ReadyClientSend
        | ZmtpHandlerPhase::ReadyServerSend => {
          trace!(fd=self.fd, phase=?self.phase, "ProcessBufferedReads: In a 'Send' phase, primarily waiting for send ACK. No read processing.");
          break 'phase_processing_loop; // No read processing in these states from this function
        }

        // Greeting Exchange (Server waiting for Client's Greeting)
        ZmtpHandlerPhase::ServerWaitClientGreeting => {
          let needed_for_greeting = GREETING_LENGTH.saturating_sub(self.greeting_buffer.len());
          if needed_for_greeting > 0 {
            let source_buf = &mut self.network_read_accumulator;
            let can_take = std::cmp::min(needed_for_greeting, source_buf.len());
            if can_take > 0 {
              self.greeting_buffer.put(source_buf.split_to(can_take));
              progress_this_iteration = true;
            }
            if self.greeting_buffer.len() < GREETING_LENGTH {
              break 'phase_processing_loop; /* Need more data for greeting */
            }
          }

          match ZmtpGreeting::decode(&mut self.greeting_buffer) {
            Ok(Some(peer_greeting)) => {
              progress_this_iteration = true;
              debug!(
                fd = self.fd,
                role = "S",
                ?peer_greeting,
                "Received and decoded client greeting"
              );
              if self.is_server == peer_greeting.as_server {
                let err = ZmqError::SecurityError("Role mismatch in greeting".into());
                self.transition_to_error(ops, err.clone(), interface);
                return Err(err);
              }
              self.security_mechanism = Some(negotiate_security_mechanism(
                self.is_server,
                &self.zmtp_config,
                &peer_greeting,
                self.fd as usize,
              )?);
              info!(fd=self.fd, mechanism=?self.security_mechanism.as_ref().unwrap().name(), "Negotiated security mechanism");

              // Server sends its greeting in response
              let mut greeting_to_send_buf = BytesMut::with_capacity(GREETING_LENGTH);
              ZmtpGreeting::encode(
                self
                  .zmtp_config
                  .security_mechanism_bytes_to_propose(self.is_server),
                true,
                &mut greeting_to_send_buf,
              );
              ops.sqe_blueprints.push(HandlerSqeBlueprint::RequestSend {
                data: greeting_to_send_buf.freeze(),
                send_op_flags: 0, // The ZMTP greeting is a single, fixed-size "frame".
                originating_app_op_ud: HANDLER_INTERNAL_SEND_OP_UD,
              });
              self.phase = ZmtpHandlerPhase::ServerSendGreeting; // Expect ACK for this send
            }
            Ok(None) => { /* Should not happen if greeting_buffer.len() == GREETING_LENGTH */ }
            Err(e) => {
              self.transition_to_error(ops, e.clone(), interface);
              return Err(e);
            }
          }
        }

        // Greeting Exchange (Client waiting for Server's Greeting) - similar to above
        ZmtpHandlerPhase::ClientWaitServerGreeting => {
          let needed_for_greeting = GREETING_LENGTH.saturating_sub(self.greeting_buffer.len());
          if needed_for_greeting > 0 {
            let source_buf = &mut self.network_read_accumulator;
            let can_take = std::cmp::min(needed_for_greeting, source_buf.len());
            if can_take > 0 {
              self.greeting_buffer.put(source_buf.split_to(can_take));
              progress_this_iteration = true;
            }
            if self.greeting_buffer.len() < GREETING_LENGTH {
              break 'phase_processing_loop;
            }
          }

          match ZmtpGreeting::decode(&mut self.greeting_buffer) {
            Ok(Some(peer_greeting)) => {
              progress_this_iteration = true;
              debug!(
                fd = self.fd,
                role = "C",
                ?peer_greeting,
                "Received and decoded server greeting"
              );
              if self.is_server == peer_greeting.as_server {
                let err = ZmqError::SecurityError("Role mismatch in greeting".into());
                self.transition_to_error(ops, err.clone(), interface);
                return Err(err);
              }
              self.security_mechanism = Some(negotiate_security_mechanism(
                self.is_server,
                &self.zmtp_config,
                &peer_greeting,
                self.fd as usize,
              )?);
              info!(fd=self.fd, mechanism=?self.security_mechanism.as_ref().unwrap().name(), "Negotiated security mechanism");
              self.phase = ZmtpHandlerPhase::SecurityExchange; // Now proceed to security token exchange
            }
            Ok(None) => {}
            Err(e) => {
              self.transition_to_error(ops, e.clone(), interface);
              return Err(e);
            }
          }
        }

        ZmtpHandlerPhase::SecurityExchange => {
          trace!(fd = self.fd, phase = ?self.phase, "ProcessBufferedReads: Entering SecurityExchange arm.");

          let mut should_transition_out_of_security_exchange = false;
          let mut mechanism_name_for_log_on_completion = "";
          let mut peer_id_from_sec_mech_on_completion: Option<Blob> = None;
          let mut mechanism_had_error = false;
          let mut error_reason_from_mechanism = String::new();

          if let Some(sec_mech_ref) = self.security_mechanism.as_mut() {
            if sec_mech_ref.is_complete() {
              info!(
                fd = self.fd,
                "SecurityExchange: Mechanism ({}) already complete. Preparing transition.",
                sec_mech_ref.name()
              );
              mechanism_name_for_log_on_completion = sec_mech_ref.name();
              peer_id_from_sec_mech_on_completion = sec_mech_ref.peer_identity().map(Blob::from);
              should_transition_out_of_security_exchange = true;
            } else {
              let mut token_action_this_iteration = false;

              // Try to produce our token. produce_token() itself should handle "whose turn".
              if let Some(token_to_send_vec) = sec_mech_ref.produce_token()? {
                debug!(
                  fd = self.fd,
                  "SecurityExchange: Producing token (len {}).",
                  token_to_send_vec.len()
                );
                let token_msg = Msg::from_vec(token_to_send_vec).with_flags(MsgFlags::COMMAND);
                // Use framer to encode/encrypt
                let wire_data = self.framer.write_msg_multipart(vec![token_msg])?;

                ops.sqe_blueprints.push(HandlerSqeBlueprint::RequestSend {
                  data: wire_data,
                  send_op_flags: 0, // Security tokens are ZMTP command frames, usually single.
                  originating_app_op_ud: HANDLER_INTERNAL_SEND_OP_UD,
                });
                progress_this_iteration = true;
                token_action_this_iteration = true;
              }

              // If there's data from the peer, try to process it.
              // We use self.framer.try_read_msg to get the token message
              if !self.network_read_accumulator.is_empty() {
                match self.framer.try_read_msg(&mut self.network_read_accumulator) {
                  Ok(Some(token_msg_from_peer)) => {
                    debug!(
                      fd = self.fd,
                      "SecurityExchange: Decoded peer token (len {}).",
                      token_msg_from_peer.size()
                    );
                    progress_this_iteration = true;
                    token_action_this_iteration = true;
                    if !token_msg_from_peer.is_command() {
                      let err_msg = "Expected ZMTP COMMAND for security token".to_string();
                      mechanism_had_error = true;
                      error_reason_from_mechanism = err_msg;
                    } else {
                      sec_mech_ref.process_token(token_msg_from_peer.data().unwrap_or_default())?;
                    }

                    // After processing peer's token, it might be our turn to send a response token.
                    // Call produce_token() again.
                    if !mechanism_had_error {
                      // Only if no error so far
                      if let Some(response_token_vec) = sec_mech_ref.produce_token()? {
                        debug!(
                          fd = self.fd,
                          "SecurityExchange: Producing response token (len {}).",
                          response_token_vec.len()
                        );
                        let response_token_msg =
                          Msg::from_vec(response_token_vec).with_flags(MsgFlags::COMMAND);
                        let wire_data =
                          self.framer.write_msg_multipart(vec![response_token_msg])?;

                        ops.sqe_blueprints.push(HandlerSqeBlueprint::RequestSend {
                          data: wire_data,
                          send_op_flags: 0,
                          originating_app_op_ud: HANDLER_INTERNAL_SEND_OP_UD,
                        });
                        // progress_this_iteration and token_action_this_iteration are likely already true
                      }
                    }
                  }
                  Ok(None) => {
                    trace!(
                      fd = self.fd,
                      "SecurityExchange: Accumulator has data, but not a full ZMTP frame for security token yet."
                    );
                  }
                  Err(e) => {
                    mechanism_had_error = true;
                    error_reason_from_mechanism =
                      format!("Failed to parse ZMTP frame for security token: {}", e);
                  }
                }
              }

              // Check mechanism status after attempting to produce/process
              // This must happen *after* any produce_token or process_token calls in this iteration.
              if !mechanism_had_error {
                // Only check these if no parsing error occurred
                if sec_mech_ref.is_complete() {
                  info!(
                    fd = self.fd,
                    "SecurityExchange: Mechanism ({}) became complete after token produce/process.",
                    sec_mech_ref.name()
                  );
                  mechanism_name_for_log_on_completion = sec_mech_ref.name();
                  peer_id_from_sec_mech_on_completion =
                    sec_mech_ref.peer_identity().map(Blob::from);
                  should_transition_out_of_security_exchange = true;
                } else if sec_mech_ref.is_error() {
                  mechanism_had_error = true; // Mark that the mechanism itself reported an error
                  error_reason_from_mechanism = sec_mech_ref
                    .error_reason()
                    .unwrap_or("Unknown security error from mechanism")
                    .to_string();
                }
              }

              // If an error occurred (either parsing or from mechanism), transition to error.
              if mechanism_had_error {
                let err = ZmqError::SecurityError(error_reason_from_mechanism.clone());
                self.transition_to_error(ops, err.clone(), interface);
                return Err(err); // Fatal error in security exchange
              }

              // If no token action was taken in this sub-iteration AND the accumulator is empty AND not yet ready to transition,
              // then we are waiting.
              if !token_action_this_iteration
                && self.network_read_accumulator.is_empty()
                && !should_transition_out_of_security_exchange
              {
                trace!(
                  fd = self.fd,
                  "SecurityExchange: No token action, buffer empty, not complete. Waiting for peer/ACK."
                );
                break 'phase_processing_loop;
              }
            }
          } else {
            let err = ZmqError::InvalidState(
              "CRITICAL: Security mechanism is None while in SecurityExchange phase.".into(),
            );
            self.transition_to_error(ops, err.clone(), interface);
            return Err(err);
          }

          if should_transition_out_of_security_exchange {
            trace!(
              fd = self.fd,
              "SecurityExchange: Executing transition post-completion."
            );

            let taken_mechanism = self.security_mechanism.take().expect(
              "INTERNAL ERROR: security_mechanism was Some but now None before take for transition",
            );

            match taken_mechanism.into_framer() {
              Ok((new_framer, peer_id_opt)) => {
                self.framer = new_framer;
                if self.peer_identity_from_security.is_none() {
                  self.peer_identity_from_security = peer_id_opt.map(Blob::from);
                }
              }
              Err(e) => {
                self.transition_to_error(ops, e, interface);
                return Err(ZmqError::Internal(
                  "Failed to create framer from mechanism".into(),
                ));
              }
            }

            let old_phase_before_transition = self.phase;
            self.phase = if self.is_server {
              ZmtpHandlerPhase::ReadyServerWaitClient
            } else {
              ZmtpHandlerPhase::ReadyClientSend
            };
            info!(fd=self.fd, old_phase=?old_phase_before_transition, new_phase=?self.phase, mech_completed=mechanism_name_for_log_on_completion, "Transitioned out of SecurityExchange.");

            if !self.is_server {
              let client_ready_msg = ZmtpReady::create_msg(self.build_ready_properties());
              debug!(
                "[ZmtpHandler FD={}] Client adding its ZMTP READY Send blueprint (from SecurityExchange transition).",
                self.fd
              );
              let wire_data = self.framer.write_msg_multipart(vec![client_ready_msg])?;

              ops.sqe_blueprints.push(HandlerSqeBlueprint::RequestSend {
                data: wire_data,
                send_op_flags: 0,
                originating_app_op_ud: HANDLER_INTERNAL_SEND_OP_UD,
              });
            } else {
              debug!(
                "[ZmtpHandler FD={}] Server finished security ({}), now in {:?} phase (from SecurityExchange transition). Waiting for client's ZMTP READY.",
                self.fd, mechanism_name_for_log_on_completion, self.phase
              );
            }
            progress_this_iteration = true;
          }
        }

        // ZMTP READY Command Exchange (Server waiting for Client's READY)
        ZmtpHandlerPhase::ReadyServerWaitClient => {
          if self.network_read_accumulator.is_empty() {
            break 'phase_processing_loop; /* Need data */
          }
          match self.framer.try_read_msg(&mut self.network_read_accumulator) {
            Ok(Some(ready_msg_from_client)) => {
              progress_this_iteration = true;
              match ZmtpCommand::parse(&ready_msg_from_client) {
                Some(ZmtpCommand::Ready(ready_data)) => {
                  debug!(
                    fd = self.fd,
                    "S: Received Client's READY. Properties: {:?}", ready_data.properties
                  );
                  if let Some(id_bytes_vec) = ready_data.properties.get("Identity") {
                    self.peer_identity_from_ready = Some(Blob::from(id_bytes_vec.clone()));
                  }

                  // Server now sends its own READY
                  let server_ready_msg = ZmtpReady::create_msg(self.build_ready_properties());
                  debug!(
                    "[ZmtpHandler FD={}] S: Adding its ZMTP READY Send blueprint.",
                    self.fd
                  );
                  let wire_data = self.framer.write_msg_multipart(vec![server_ready_msg])?;

                  ops.sqe_blueprints.push(HandlerSqeBlueprint::RequestSend {
                    data: wire_data,
                    send_op_flags: 0,
                    originating_app_op_ud: HANDLER_INTERNAL_SEND_OP_UD,
                  });
                  self.phase = ZmtpHandlerPhase::ReadyServerSend;
                }
                _ => {
                  let err = ZmqError::ProtocolViolation(
                    "S: Expected READY from client, got other/unparseable".into(),
                  );
                  self.transition_to_error(ops, err.clone(), interface);
                  return Err(err);
                }
              }
            }
            Ok(None) => {
              break 'phase_processing_loop; /* Need more data for client's READY */
            }
            Err(e) => {
              self.transition_to_error(ops, e.clone(), interface);
              return Err(e);
            }
          }
        }

        // ZMTP READY Command Exchange (Client waiting for Server's READY)
        ZmtpHandlerPhase::ReadyClientWaitServer => {
          if self.network_read_accumulator.is_empty() {
            break 'phase_processing_loop; /* Need data */
          }
          match self.framer.try_read_msg(&mut self.network_read_accumulator) {
            Ok(Some(ready_msg_from_server)) => {
              progress_this_iteration = true;
              match ZmtpCommand::parse(&ready_msg_from_server) {
                Some(ZmtpCommand::Ready(ready_data)) => {
                  debug!(
                    fd = self.fd,
                    "C: Received Server's READY. Properties: {:?}", ready_data.properties
                  );
                  if let Some(id_bytes_vec) = ready_data.properties.get("Identity") {
                    self.peer_identity_from_ready = Some(Blob::from(id_bytes_vec.clone()));
                  }
                  // Client handshake fully complete
                  self.phase = ZmtpHandlerPhase::DataPhase;
                  info!(
                    fd = self.fd,
                    "ZmtpUringHandler: Client handshake fully complete. Transitioning to DataPhase."
                  );
                  self.signal_upstream_handshake_complete(interface)?;
                }
                _ => {
                  let err = ZmqError::ProtocolViolation(
                    "C: Expected READY from server, got other/unparseable".into(),
                  );
                  self.transition_to_error(ops, err.clone(), interface);
                  return Err(err);
                }
              }
            }
            Ok(None) => {
              break 'phase_processing_loop; /* Need more data for server's READY */
            }
            Err(e) => {
              self.transition_to_error(ops, e.clone(), interface);
              return Err(e);
            }
          }
        }

        ZmtpHandlerPhase::DataPhase => {
          // Framer handles accumulating bytes, checking length, decrypting, and parsing.
          loop {
            match self.framer.try_read_msg(&mut self.network_read_accumulator) {
              Ok(Some(msg)) => {
                progress_this_iteration = true;
                self.last_activity_time = Instant::now();

                if msg.is_command() {
                  match ZmtpCommand::parse(&msg) {
                    Some(ZmtpCommand::Ping(ping_context_payload)) => {
                      let pong_reply_msg = ZmtpCommand::create_pong(&ping_context_payload);
                      // Use framer to write the PONG
                      let wire_bytes = self.framer.write_msg_multipart(vec![pong_reply_msg])?;

                      ops.sqe_blueprints.push(HandlerSqeBlueprint::RequestSend {
                        data: wire_bytes,
                        send_op_flags: 0,
                        originating_app_op_ud: HANDLER_INTERNAL_SEND_OP_UD,
                      });
                      debug!(fd = self.fd, "DataPhase: Prepared PONG in response to PING");
                    }
                    Some(ZmtpCommand::Pong(_pong_context_payload)) => {
                      self.waiting_for_pong = false;
                      self.last_ping_sent_time = None;
                      debug!(fd = self.fd, "DataPhase: Received PONG");
                    }
                    Some(ZmtpCommand::Error) => {
                      warn!(fd = self.fd, "DataPhase: Peer sent ZMTP ERROR command.");
                      let err = ZmqError::ProtocolViolation("Peer sent ZMTP ERROR command".into());
                      self.transition_to_error(ops, err.clone(), interface);
                      return Err(err);
                    }
                    _ => {
                      warn!(
                        fd = self.fd,
                        "DataPhase: Received unhandled ZMTP command: {:?}",
                        msg.data()
                      );
                    }
                  }
                } else {
                  // Data message
                  let upstream_event = HandlerUpstreamEvent::Data(msg);
                  if let Err(send_err) = interface
                    .worker_io_config
                    .upstream_event_tx
                    .try_send((self.fd, upstream_event))
                  {
                    error!(
                      fd = self.fd,
                      "DataPhase: Failed to send ZMTP data msg upstream: {:?}", send_err
                    );
                    let err = ZmqError::Internal("Upstream channel error for ZMTP data".into());
                    self.transition_to_error(ops, err.clone(), interface);
                    return Err(err);
                  }
                }
              }
              Ok(None) => break, // Need more network data
              Err(e) => {
                self.transition_to_error(ops, e.clone(), interface);
                return Err(e);
              }
            }
          }
        }
        ZmtpHandlerPhase::Closing => {
          // If we are in the closing state, we should not process any more data from the buffers.
          // Just wait for the close operation to complete.
          trace!(fd=self.fd, phase=?self.phase, "ProcessBufferedReads: In Closing phase, ignoring buffered data.");
          break 'phase_processing_loop;
        }
        ZmtpHandlerPhase::Error | ZmtpHandlerPhase::Closed => {
          break 'phase_processing_loop; // Final states, no more processing
        }
      } // End match self.phase

      made_progress_this_call |= progress_this_iteration;

      // Check if loop should continue:
      // If no data was consumed from any buffer, and no other progress (like phase change) was made in *this iteration*, break.
      let no_greeting_change_outer = self.greeting_buffer.len() == initial_greeting_len_outer;
      let no_network_acc_change_outer =
        self.network_read_accumulator.len() == initial_network_acc_len_outer;

      // Removed plaintext accumulator check

      if no_greeting_change_outer && no_network_acc_change_outer && !progress_this_iteration {
        trace!(fd=self.fd, phase=?self.phase, "ProcessBufferedReads: No data consumed or progress in this iteration. Breaking inner loop.");
        break 'phase_processing_loop;
      }
      // If progress was made (data consumed or phase changed), allow loop to continue to re-evaluate with new state/buffers.
      // Reset for next iteration of outer loop.
      // made_progress_this_call is accumulated across iterations of this outer loop
    } // End 'phase_processing_loop

    Ok(made_progress_this_call) // Return overall progress
  }

  // Helper method to prepare the logical frames (e.g. delimiters) before passing to framer.
  // Returns Vec<Msg> which will be passed to self.framer.write_msg_multipart.
  fn prepare_logical_frames_for_app_msg(&mut self, app_msg: Msg) -> Vec<Msg> {
    let mut frames = Vec::new();

    // Example for REQ/DEALER like sockets that prepend an empty delimiter
    if self.zmtp_config.socket_type_name == "REQ" || self.zmtp_config.socket_type_name == "DEALER" {
      let delimiter_msg = Msg::new().with_flags(MsgFlags::MORE);
      frames.push(delimiter_msg);
    }

    // Prepare the main payload part
    let mut payload_part = app_msg;
    // Ensure the app-level payload, when it becomes the last ZMTP frame, has NOMORE.
    payload_part.set_flags(payload_part.flags() & !MsgFlags::MORE);
    frames.push(payload_part);

    frames
  }

  /// Helper to take final ZMTP wire frames, decide on ZC/normal send,
  /// and add appropriate blueprints to HandlerIoOps.
  fn add_send_blueprints_for_wire_frames(
    &self,                         // Needs &self to access zmtp_config and ZC_SEND_THRESHOLD
    final_wire_frames: Vec<Bytes>, // Already ZMTP encoded & encrypted
    originating_op_ud_for_blueprints: UserData, // Actual app UD or sentinel
    ops: &mut HandlerIoOps,
  ) {
    let num_final_wire_frames = final_wire_frames.len();
    if num_final_wire_frames == 0 {
      // This case should ideally be handled by the caller (e.g., prepare_zmtp_wire_frames_for_app_msg
      // should not return an empty Vec unless it's a valid ZMTP way to send "nothing").
      // For PUSH, an empty app message might mean nothing is sent.
      trace!(
        fd = self.fd,
        op_ud = originating_op_ud_for_blueprints,
        "add_send_blueprints_for_wire_frames called with empty wire frames. No blueprints added."
      );
      return;
    }

    let should_cork =
      num_final_wire_frames > 1 && self.zmtp_config.use_cork && cfg!(target_os = "linux");

    if should_cork {
      trace!(
        fd = self.fd,
        "ZmtpHandler: Adding RequestSetCork(true) blueprint."
      );
      ops
        .sqe_blueprints
        .push(HandlerSqeBlueprint::RequestSetCork(true));
    }

    for (idx, final_wire_bytes_for_part) in final_wire_frames.into_iter().enumerate() {
      let is_last_logical_part = idx == num_final_wire_frames - 1;
      let send_op_flags: i32 = if is_last_logical_part {
        0
      } else {
        libc::MSG_MORE
      };

      if self.zmtp_config.use_send_zerocopy && final_wire_bytes_for_part.len() > ZC_SEND_THRESHOLD {
        trace!(
          fd = self.fd,
          len = final_wire_bytes_for_part.len(),
          part_idx = idx,
          app_op_ud = originating_op_ud_for_blueprints,
          "ZmtpHandler (helper): Attempting ZC send."
        );
        ops
          .sqe_blueprints
          .push(HandlerSqeBlueprint::RequestSendZeroCopy {
            data_to_send: final_wire_bytes_for_part,
            send_op_flags,
            originating_app_op_ud: originating_op_ud_for_blueprints,
          });
      } else {
        trace!(
          fd = self.fd,
          len = final_wire_bytes_for_part.len(),
          part_idx = idx,
          app_op_ud = originating_op_ud_for_blueprints,
          zc_enabled = self.zmtp_config.use_send_zerocopy,
          "ZmtpHandler (helper): Using normal send."
        );
        ops.sqe_blueprints.push(HandlerSqeBlueprint::RequestSend {
          data: final_wire_bytes_for_part,
          send_op_flags,
          originating_app_op_ud: originating_op_ud_for_blueprints,
        });
      }
    }

    if should_cork {
      trace!(
        fd = self.fd,
        "ZmtpHandler: Adding RequestSetCork(false) blueprint."
      );
      ops
        .sqe_blueprints
        .push(HandlerSqeBlueprint::RequestSetCork(false));
    }
  }

  pub fn is_closing_or_closed(&self) -> bool {
    matches!(
      self.phase,
      ZmtpHandlerPhase::Closing | ZmtpHandlerPhase::Closed | ZmtpHandlerPhase::Error
    )
  }

  /// Helper to take final ZMTP wire bytes (from framer), decide on ZC/normal send,
  /// and add appropriate blueprints to HandlerIoOps.
  fn add_send_blueprints_for_wire_bytes(
    &self,
    final_wire_bytes: Bytes, // Already ZMTP encoded & encrypted by framer
    originating_op_ud_for_blueprints: UserData,
    ops: &mut HandlerIoOps,
  ) {
    if final_wire_bytes.is_empty() {
      return;
    }

    // Framer produces one contiguous Bytes buffer for the whole batch.
    // We don't need manual corking logic here for a single buffer write.

    if self.zmtp_config.use_send_zerocopy && final_wire_bytes.len() > ZC_SEND_THRESHOLD {
      trace!(
        fd = self.fd,
        len = final_wire_bytes.len(),
        app_op_ud = originating_op_ud_for_blueprints,
        "ZmtpHandler (helper): Attempting ZC send."
      );
      ops
        .sqe_blueprints
        .push(HandlerSqeBlueprint::RequestSendZeroCopy {
          data_to_send: final_wire_bytes,
          send_op_flags: 0,
          originating_app_op_ud: originating_op_ud_for_blueprints,
        });
    } else {
      trace!(
        fd = self.fd,
        len = final_wire_bytes.len(),
        app_op_ud = originating_op_ud_for_blueprints,
        "ZmtpHandler (helper): Using normal send."
      );
      ops.sqe_blueprints.push(HandlerSqeBlueprint::RequestSend {
        data: final_wire_bytes,
        send_op_flags: 0,
        originating_app_op_ud: originating_op_ud_for_blueprints,
      });
    }
  }
}

impl UringConnectionHandler for ZmtpUringHandler {
  fn fd(&self) -> RawFd {
    self.fd
  }

  fn is_closing_or_closed(&self) -> bool {
    // Delegate to the public helper method we already created.
    self.is_closing_or_closed()
  }

  fn connection_ready(&mut self, interface: &UringWorkerInterface<'_>) -> HandlerIoOps {
    info!(
      fd = self.fd,
      role = if self.is_server { "S" } else { "C" },
      "ZmtpUringHandler: connection_ready."
    );
    self.last_activity_time = Instant::now();
    self.handshake_timeout_deadline = Instant::now() + self.handshake_timeout;
    let mut ops = HandlerIoOps::new();

    if self.zmtp_config.use_recv_multishot {
      // Assuming ZmtpEngineConfig has this field
      if let Some(bgid) = interface.default_buffer_group_id() {
        self.multishot_reader = Some(MultishotReader::new(self.fd, bgid));
        tracing::debug!(
          "[ZmtpUringHandler FD={}] MultishotReader initialized. Initial read will be requested via prepare_sqes.",
          self.fd
        );
        // The actual RequestRingReadMultishot blueprint will be added by prepare_sqes.
      } else {
        tracing::error!(
          "[ZmtpUringHandler FD={}] Multishot configured (use_recv_multishot=true) but no default_bgid available from worker interface! Falling back to standard reads.",
          self.fd
        );
      }
    }

    if self.is_server {
      self.phase = ZmtpHandlerPhase::ServerWaitClientGreeting;
    } else {
      let mut greeting_to_send_buf = BytesMut::with_capacity(GREETING_LENGTH);
      let proposed_mechanism_bytes = self
        .zmtp_config
        .security_mechanism_bytes_to_propose(self.is_server);
      ZmtpGreeting::encode(proposed_mechanism_bytes, false, &mut greeting_to_send_buf);
      ops.sqe_blueprints.push(HandlerSqeBlueprint::RequestSend {
        data: greeting_to_send_buf.freeze(),
        send_op_flags: 0, // Greeting is a single "frame".
        originating_app_op_ud: HANDLER_INTERNAL_SEND_OP_UD,
      });
      self.phase = ZmtpHandlerPhase::ClientSendGreeting;
    }

    ops
  }

  fn process_ring_read_data(
    &mut self,
    buffer_slice: &[u8],
    _buffer_id: u16,
    interface: &UringWorkerInterface<'_>,
  ) -> HandlerIoOps {
    trace!(fd = self.fd, len = buffer_slice.len(), phase = ?self.phase, "ZmtpUringHandler: process_ring_read_data");
    self.last_activity_time = Instant::now();

    let mut ops = HandlerIoOps::new();

    if buffer_slice.is_empty()
      && !matches!(
        self.phase,
        ZmtpHandlerPhase::Closed | ZmtpHandlerPhase::Error
      )
    {
      let original_phase_eof = self.phase;
      info!(
        fd = self.fd,
        ?original_phase_eof,
        "Peer closed connection (EOF received on read)."
      );
      let eof_err = ZmqError::ConnectionClosed;

      if let Some(reader) = &mut self.multishot_reader {
        if reader.is_active() {
          // The `interface` doesn't easily provide `InternalOpTracker` here.
          // `prepare_cancel_blueprint` in MultishotReader needs it.
          // This suggests that either `process_ring_read_data` needs the tracker,
          // or cancellation due to EOF is handled differently (e.g. by `cqe_processor`
          // which *can* call `reader.prepare_cancel_blueprint` with the tracker).
          // For now, we'll just transition to error and let `close_initiated` handle cancel.
          tracing::info!(
            "[ZmtpUringHandler FD={}] EOF received, multishot was active. Will be cancelled during close_initiated.",
            self.fd
          );
        }
      }

      let mut temp_ops = std::mem::take(&mut ops);
      self.transition_to_error(&mut temp_ops, eof_err.clone(), interface); // Pass clone
      ops = temp_ops;
      // Also ensure the error is sent upstream if transition_to_error didn't send it (e.g., if already in DataPhase)
      if matches!(original_phase_eof, ZmtpHandlerPhase::DataPhase) {
        let _ = interface
          .worker_io_config
          .upstream_event_tx
          .try_send((self.fd, HandlerUpstreamEvent::Error(eof_err)));
      }

      return ops;
    }

    if !buffer_slice.is_empty() {
      self.network_read_accumulator.put_slice(buffer_slice);
    }

    if let Err(e) = self.process_buffered_reads(interface, &mut ops) {
      if self.phase != ZmtpHandlerPhase::Error && self.phase != ZmtpHandlerPhase::Closed {
        error!(fd = self.fd, error = %e, "process_buffered_reads returned error but phase not Error/Closed. Forcing error state.");
        let mut temp_ops = std::mem::take(&mut ops);
        self.transition_to_error(&mut temp_ops, e, interface);
        ops = temp_ops;
      }
    }

    ops
  }

  fn handle_internal_sqe_completion(
    &mut self,
    sqe_user_data: UserData,
    cqe_result: i32,
    _cqe_flags: u32,
    interface: &UringWorkerInterface<'_>,
  ) -> HandlerIoOps {
    trace!(fd = self.fd, cqe_res = cqe_result, phase = ?self.phase, "ZmtpUringHandler: handle_internal_sqe_completion (likely Send ACK)");
    self.last_activity_time = Instant::now();
    let mut ops = HandlerIoOps::new();

    if cqe_result < 0 {
      let raw_errno = -cqe_result;
      if raw_errno == libc::EAGAIN || raw_errno == libc::EWOULDBLOCK {
        // This is not a real error. It just means the read operation found no data.
        // We simply need to request another read for the future.
        trace!(
          fd = self.fd,
          ud = sqe_user_data,
          "Read operation completed with EAGAIN/EWOULDBLOCK. This is normal. Requesting new read."
        );
        // The `ensure_standard_read_is_pending` call at the end of this function
        // will now correctly queue a new read since `pending_read_op_ud` was just cleared.
      } else {
        // This is a real, fatal kernel error.
        let io_err = std::io::Error::from_raw_os_error(raw_errno);
        let zmq_err = ZmqError::from(io_err);
        // The log message "Kernel error on send operation" is a bit misleading, as this
        // could also be a read error. Let's make it more generic.
        error!(fd = self.fd, error = %zmq_err, "Fatal kernel error on I/O operation.");
        let mut temp_ops = std::mem::take(&mut ops);
        self.transition_to_error(&mut temp_ops, zmq_err, interface);
        ops = temp_ops;
        return ops;
      }
    }

    let previous_phase = self.phase;
    match self.phase {
      ZmtpHandlerPhase::ClientSendGreeting => {
        self.phase = ZmtpHandlerPhase::ClientWaitServerGreeting;
      }
      ZmtpHandlerPhase::ServerSendGreeting => {
        self.phase = ZmtpHandlerPhase::SecurityExchange;
        if let Some(sec_mech) = self.security_mechanism.as_mut() {
          if let Ok(Some(token_vec)) = sec_mech.produce_token() {
            // produce_token() decides if it's turn.
            let token_msg = Msg::from_vec(token_vec).with_flags(MsgFlags::COMMAND);

            // Modified to use Framer
            match self.framer.write_msg_multipart(vec![token_msg]) {
              Ok(bytes) => {
                ops.sqe_blueprints.push(HandlerSqeBlueprint::RequestSend {
                  data: bytes,
                  send_op_flags: 0, // Security tokens are ZMTP command frames, usually single.
                  originating_app_op_ud: HANDLER_INTERNAL_SEND_OP_UD, // Internal protocol message.
                });
              }
              Err(err) => {
                let err = ZmqError::Internal(format!(
                  "Failed to encode/encrypt server security token: {}",
                  err
                ));
                let mut temp_ops = std::mem::take(&mut ops);
                self.transition_to_error(&mut temp_ops, err, interface);
                ops = temp_ops;
                return ops;
              }
            }
          }
        }
      }
      ZmtpHandlerPhase::SecurityExchange | ZmtpHandlerPhase::Closing => {}
      ZmtpHandlerPhase::ReadyClientSend => {
        self.phase = ZmtpHandlerPhase::ReadyClientWaitServer;
      }
      ZmtpHandlerPhase::ReadyServerSend => {
        self.phase = ZmtpHandlerPhase::DataPhase;
        info!(
          fd = self.fd,
          "ZmtpUringHandler: Server handshake fully complete. Transitioning to DataPhase."
        );
        if let Err(e) = self.signal_upstream_handshake_complete(interface) {
          let mut temp_ops = std::mem::take(&mut ops);
          self.transition_to_error(&mut temp_ops, e, interface);
          ops = temp_ops;
          return ops;
        }
      }
      ZmtpHandlerPhase::DataPhase => {
        if self.last_sent_was_ping {
          self.waiting_for_pong = true;
          self.last_ping_sent_time = Some(self.last_activity_time);
          debug!(
            fd = self.fd,
            "PING send acknowledged by kernel. Now waiting for PONG reply."
          );
          self.last_sent_was_ping = false;
        }

        if let Some((multipart_msg_parts, queued_originating_app_op_ud)) =
          self.outgoing_multipart_app_messages.pop_front()
        {
          // Modified to use Framer
          match self.framer.write_msg_multipart(multipart_msg_parts.clone()) {
            Ok(wire_bytes_to_send) => {
              self.add_send_blueprints_for_wire_bytes(
                wire_bytes_to_send,
                queued_originating_app_op_ud,
                &mut ops,
              );
            }
            Err(e) => {
              /* error handling, potentially re-queue with UD or handle error */
              error!(
                fd = self.fd,
                "Failed to frame/encrypt queued multipart message: {}. Message dropped from queue.",
                e
              );
              // Re-queue the original parts along with their UserData on failure
              self
                .outgoing_multipart_app_messages
                .push_front((multipart_msg_parts, queued_originating_app_op_ud));
              // Potentially transition to error or handle differently based on error type
              self.transition_to_error(&mut ops, e, interface); // Assuming interface is available
              return ops; // Or continue if error is not fatal for other operations
            }
          }
        } else if let Some((next_app_msg, queued_originating_app_op_ud)) =
          self.outgoing_app_messages.pop_front()
        {
          // Modified to use Framer via logic helper
          // For PUSH, this might be one frame. For REQ/DEALER, it's [delimiter, payload].
          let logical_frames = self.prepare_logical_frames_for_app_msg(next_app_msg.clone());

          match self.framer.write_msg_multipart(logical_frames) {
            Ok(wire_bytes_to_send) => {
              self.add_send_blueprints_for_wire_bytes(
                wire_bytes_to_send,
                queued_originating_app_op_ud,
                &mut ops,
              );
            }
            Err(e) => {
              error!(
                fd = self.fd,
                "Failed to frame/encrypt queued single message: {}. Re-queuing.", e
              );
              // Re-queue the original app message and its UserData on failure
              self
                .outgoing_app_messages
                .push_front((next_app_msg, queued_originating_app_op_ud));
              self.transition_to_error(&mut ops, e, interface); // Assuming interface is available
              return ops; // Or continue
            }
          }
        }
      }
      _ => {
        warn!(fd = self.fd, phase = ?previous_phase, "Send completion (ack) received in unexpected phase.");
      }
    }

    if self.phase != previous_phase
      && (!self.greeting_buffer.is_empty() || !self.network_read_accumulator.is_empty())
    {
      if let Err(e) = self.process_buffered_reads(interface, &mut ops) {
        if self.phase != ZmtpHandlerPhase::Error && self.phase != ZmtpHandlerPhase::Closed {
          let mut temp_ops = std::mem::take(&mut ops);
          self.transition_to_error(&mut temp_ops, e, interface);
          ops = temp_ops;
        }
      }
    }

    ops
  }

  fn prepare_sqes(&mut self, interface: &UringWorkerInterface<'_>) -> HandlerIoOps {
    let mut ops = HandlerIoOps::new();

    if Instant::now() > self.handshake_timeout_deadline
      && !matches!(
        self.phase,
        ZmtpHandlerPhase::DataPhase | ZmtpHandlerPhase::Error | ZmtpHandlerPhase::Closed
      )
    {
      warn!(fd = self.fd, current_phase=?self.phase, "Overall handshake timeout occurred in prepare_sqes.");
      let err = ZmqError::Timeout;
      let mut temp_ops = std::mem::take(&mut ops);
      self.transition_to_error(&mut temp_ops, err.clone(), interface);
      ops = temp_ops;
      return ops;
    }

    if let Some(reader) = &mut self.multishot_reader {
      if !reader.is_active() {
        // Use the reader's state
        if let Some(blueprint) = reader.prepare_recv_multi_intent() {
          ops.sqe_blueprints.push(blueprint);
        }
      }
    }

    if self.phase == ZmtpHandlerPhase::DataPhase {
      if ops.sqe_blueprints.is_empty() {
        if let Some((multipart_app_parts, queued_originating_app_op_ud)) =
          self.outgoing_multipart_app_messages.pop_front()
        {
          // Modified to use Framer
          match self.framer.write_msg_multipart(multipart_app_parts.clone()) {
            // Clone for potential re-queue
            Ok(wire_bytes_to_send) => {
              // wire_bytes_to_send is Bytes
              self.add_send_blueprints_for_wire_bytes(
                wire_bytes_to_send,
                queued_originating_app_op_ud,
                &mut ops, // ops is the HandlerIoOps being built
              );
            }
            Err(e) => {
              error!(
                fd = self.fd,
                "Failed to frame/encrypt multipart message from queue in prepare_sqes: {}. Re-queuing.",
                e
              );
              self
                .outgoing_multipart_app_messages
                .push_front((multipart_app_parts, queued_originating_app_op_ud));
              // Ensure 'interface' is available if this code is in a place where it's not a direct argument
              // For 'prepare_sqes', 'interface' IS an argument.
              let mut temp_ops_taken = std::mem::take(&mut ops); // To pass &mut ops to transition_to_error
              self.transition_to_error(&mut temp_ops_taken, e, interface);
              ops = temp_ops_taken;
              // Depending on function's return type, may need to `return ops;` or handle error propagation
            }
          }
        } else if let Some((app_msg_to_send, queued_originating_app_op_ud)) =
          self.outgoing_app_messages.pop_front()
        {
          // Modified to use Framer via logic helper
          let logical_frames = self.prepare_logical_frames_for_app_msg(app_msg_to_send.clone());

          match self.framer.write_msg_multipart(logical_frames) {
            Ok(wire_bytes_to_send) => {
              self.add_send_blueprints_for_wire_bytes(
                wire_bytes_to_send,
                queued_originating_app_op_ud,
                &mut ops,
              );
            }
            Err(e) => {
              error!(
                fd = self.fd,
                "Failed to frame/encrypt queued single message: {}. Re-queuing.", e
              );
              self
                .outgoing_app_messages
                .push_front((app_msg_to_send, queued_originating_app_op_ud));
              let mut temp_ops_taken = std::mem::take(&mut ops);
              self.transition_to_error(&mut temp_ops_taken, e, interface);
              ops = temp_ops_taken;
              // return ops; or handle error
            }
          }
        } else if ops.sqe_blueprints.is_empty() {
          let now = Instant::now();
          if self.waiting_for_pong {
            if let Some(ping_sent_at) = self.last_ping_sent_time {
              if now.duration_since(ping_sent_at) > self.heartbeat_timeout_duration {
                warn!(
                  fd = self.fd,
                  "PONG timeout in prepare_sqes. Transitioning to error."
                );
                let err = ZmqError::Timeout;
                let mut temp_ops = std::mem::take(&mut ops);
                self.transition_to_error(&mut temp_ops, err.clone(), interface);
                ops = temp_ops;
              }
            }
          } else if let Some(ivl) = self.heartbeat_ivl {
            if now.duration_since(self.last_activity_time) >= ivl {
              debug!(fd = self.fd, "Heartbeat interval elapsed. Preparing PING.");
              let ping_msg = ZmtpCommand::create_ping(0, b"hb_ping");

              // Modified to use Framer
              match self.framer.write_msg_multipart(vec![ping_msg]) {
                Ok(ping_wire_bytes) => {
                  ops.sqe_blueprints.push(HandlerSqeBlueprint::RequestSend {
                    data: ping_wire_bytes,
                    send_op_flags: 0,
                    originating_app_op_ud: HANDLER_INTERNAL_SEND_OP_UD,
                  });
                  self.last_sent_was_ping = true;
                }
                Err(e) => {
                  error!(fd = self.fd, "Failed to frame PING: {}", e);
                  let mut temp_ops = std::mem::take(&mut ops);
                  self.transition_to_error(&mut temp_ops, e, interface);
                  ops = temp_ops;
                }
              }
            }
          }
        }
      }
    }
    ops
  }

  fn handle_outgoing_app_data(
    &mut self,
    data: Arc<dyn Any + Send + Sync>,
    interface: &UringWorkerInterface<'_>,
  ) -> HandlerIoOps {
    let mut ops = HandlerIoOps::new();
    let originating_app_op_ud = interface.current_external_op_ud;

    match DowncastArcAny::downcast_arc::<Vec<Msg>>(data.clone()) {
      Ok(app_data_parts_arc) => {
        // Multipart message
        let app_data_parts_vec = (*app_data_parts_arc).clone();
        if self.phase == ZmtpHandlerPhase::DataPhase
          && self.outgoing_app_messages.is_empty()
          && self.outgoing_multipart_app_messages.is_empty()
        {
          match self.framer.write_msg_multipart(app_data_parts_vec.clone()) {
            Ok(wire_bytes) => {
              self.add_send_blueprints_for_wire_bytes(wire_bytes, originating_app_op_ud, &mut ops);
            }
            Err(e) => {
              error!(
                fd = self.fd,
                "Failed to encode/encrypt outgoing multipart app data: {}. Queuing.", e
              );
              self
                .outgoing_multipart_app_messages
                .push_back((app_data_parts_vec, originating_app_op_ud));
            }
          }
        } else {
          trace!(fd = self.fd, phase = ?self.phase, "Queuing outgoing multipart app data ({} parts).", app_data_parts_vec.len());
          self
            .outgoing_multipart_app_messages
            .push_back((app_data_parts_vec, originating_app_op_ud));
        }
      }
      Err(original_arc_any) => {
        // Not Arc<Vec<Msg>>, try Arc<Msg> (single part)
        match DowncastArcAny::downcast_arc::<Msg>(original_arc_any) {
          Ok(msg_arc) => {
            let msg_to_send_app_level = (*msg_arc).clone(); // This is the single app-level Msg
            if self.phase == ZmtpHandlerPhase::DataPhase
              && self.outgoing_app_messages.is_empty()
              && self.outgoing_multipart_app_messages.is_empty()
            {
              // This is the part that needs to correctly prepare the *full sequence*
              // of ZMTP wire frames for a single application-level message.
              // For PUSH, this might be one frame. For REQ/DEALER, it's [delimiter, payload].
              // Let's assume a helper method `prepare_wire_frames_for_app_msg` exists
              // that takes the app `Msg` and returns `Result<Vec<Bytes>, ZmqError>`,
              // where each `Bytes` is a fully ZMTP-encoded and encrypted wire frame.
              let logical_frames =
                self.prepare_logical_frames_for_app_msg(msg_to_send_app_level.clone());

              match self.framer.write_msg_multipart(logical_frames) {
                Ok(wire_bytes) => {
                  self.add_send_blueprints_for_wire_bytes(
                    wire_bytes,
                    originating_app_op_ud,
                    &mut ops,
                  );
                }
                Err(e) => {
                  error!(
                    fd = self.fd,
                    "Failed to prepare wire frames for single app message: {}. Queuing.", e
                  );
                  self
                    .outgoing_app_messages
                    .push_back((msg_to_send_app_level, originating_app_op_ud));
                }
              }
            } else {
              trace!(fd = self.fd, phase = ?self.phase, "Queuing outgoing single-part app data.");
              self
                .outgoing_app_messages
                .push_back((msg_to_send_app_level, originating_app_op_ud));
            }
          }
          Err(_unhandled_arc_any) => {
            error!(
              fd = self.fd,
              "ZmtpUringHandler received unknown app data type. Ignoring."
            );
          }
        }
      }
    }

    ops
  }

  fn close_initiated(&mut self, _interface: &UringWorkerInterface<'_>) -> HandlerIoOps {
    info!(
      fd = self.fd,
      "ZmtpUringHandler: close_initiated called. Worker will handle cancellation and close."
    );

    // If already closing/closed, do nothing further.
    if self.is_closing_or_closed() {
      return HandlerIoOps::new();
    }

    // Transition to the Closing state.
    self.phase = ZmtpHandlerPhase::Closing;
    self.outgoing_app_messages.clear();
    self.outgoing_multipart_app_messages.clear();

    // The handler's job is done. It no longer needs to generate blueprints for close/cancel.
    // The worker, upon receiving ShutdownConnectionHandler, now orchestrates the cancellation and close.
    // Return empty ops.
    HandlerIoOps::new()
  }

  fn fd_has_been_closed(&mut self) {
    info!(
      fd = self.fd,
      "ZmtpUringHandler: fd_has_been_closed notification received."
    );
    self.phase = ZmtpHandlerPhase::Closed;
  }

  fn delegate_cqe_to_multishot_reader(
    &mut self,
    cqe: &io_uring::cqueue::Entry, // Pass the full CQE
    buffer_manager: &BufferRingManager,
    worker_interface: &UringWorkerInterface<'_>,
    internal_op_tracker: &mut InternalOpTracker,
  ) -> Option<Result<(HandlerIoOps, bool), ZmqError>> {
    // bool is should_cleanup_active_op_ud
    let cqe_user_data = cqe.user_data();

    // Immutable check first to see if the reader exists and if the UserData might match.
    let reader_might_handle = self
      .multishot_reader
      .as_ref()
      .map_or(false, |r| r.matches_cqe_user_data(cqe_user_data));

    if reader_might_handle {
      // If it might handle, take the reader mutably to process the CQE.
      // This pattern (take, process, put_back) is crucial to avoid borrow checker issues
      // when `MultishotReader::process_cqe` calls `self.process_ring_read_data`.
      if let Some(mut reader) = self.multishot_reader.take() {
        let result_tuple = reader.process_cqe(
          cqe,
          buffer_manager,
          self, // `self` (ZmtpUringHandler) is passed as `owner_handler`
          worker_interface,
          internal_op_tracker,
        );
        // Put the reader back after processing
        self.multishot_reader = Some(reader);
        return Some(result_tuple);
      } else {
        // This case should ideally not be reached if `reader_might_handle` was true
        // and `self.multishot_reader` was Some. It implies a logic error or race if
        // another part of the code could also `take()` the reader.
        tracing::error!(
          "[ZmtpUringHandler FD={}] Inconsistent state in delegate_cqe_to_multishot_reader: \
                    reader_might_handle was true, but multishot_reader was None on take(). CQE UserData: {}",
          self.fd,
          cqe_user_data
        );
        // Fall through to return None, indicating CQE was not handled by multishot logic here.
      }
    }
    None // CQE not for an active multishot reader of this handler, or no reader.
  }

  fn inform_multishot_reader_op_submitted(
    &mut self,
    op_user_data: UserData,
    is_cancel_op: bool,
    target_op_data_if_cancel: Option<UserData>,
  ) {
    if let Some(reader) = &mut self.multishot_reader {
      if is_cancel_op {
        if let Some(target_ud) = target_op_data_if_cancel {
          reader.mark_cancellation_submitted(op_user_data, target_ud);
        } else {
          tracing::warn!(
            "[ZmtpHandler FD={}] inform_multishot_reader_op_submitted called for cancel_op but target_op_data_if_cancel is None.",
            self.fd
          );
        }
      } else {
        reader.mark_operation_submitted(op_user_data);
      }
    } else {
      tracing::warn!(
        "[ZmtpHandler FD={}] inform_multishot_reader_op_submitted called but no multishot_reader exists.",
        self.fd
      );
    }
  }
}

pub struct ZmtpHandlerFactory {}

impl ProtocolHandlerFactory for ZmtpHandlerFactory {
  fn id(&self) -> &'static str {
    "zmtp-uring/3.1"
  }

  fn create_handler(
    &self,
    fd: RawFd,
    _worker_io_config: Arc<WorkerIoConfig>,
    protocol_config: &ProtocolConfig,
    is_server_role: bool,
  ) -> Result<Box<dyn UringConnectionHandler + Send>, String> {
    match protocol_config {
      ProtocolConfig::Zmtp(engine_config_arc) => Ok(Box::new(ZmtpUringHandler::new(
        fd,
        engine_config_arc.clone(),
        is_server_role,
      ))),
      #[allow(unreachable_patterns)]
      _ => Err(format!(
        "ZmtpHandlerFactory (id: '{}') received an incompatible ProtocolConfig variant: {:?}",
        self.id(),
        protocol_config
      )),
    }
  }
}

trait DowncastArcAny {
  fn downcast_arc<T: Any + Send + Sync>(self) -> Result<Arc<T>, Self>
  where
    Self: Sized;
}
impl DowncastArcAny for Arc<dyn Any + Send + Sync> {
  fn downcast_arc<T: Any + Send + Sync>(self) -> Result<Arc<T>, Self> {
    if self.is::<T>() {
      unsafe { Ok(Arc::from_raw(Arc::into_raw(self).cast::<T>())) }
    } else {
      Err(self)
    }
  }
}

trait MsgWithFlags {
  fn with_flags(self, flags: MsgFlags) -> Self;
}
impl MsgWithFlags for Msg {
  fn with_flags(mut self, flags: MsgFlags) -> Self {
    self.set_flags(flags);
    self
  }
}

trait ZmtpConfigSecurityExt {
  fn security_mechanism_bytes_to_propose(
    &self,
    is_handler_server_role: bool,
  ) -> &'static [u8; MECHANISM_LENGTH];
}
impl ZmtpConfigSecurityExt for ZmtpEngineConfig {
  fn security_mechanism_bytes_to_propose(
    &self,
    is_handler_server_role: bool,
  ) -> &'static [u8; MECHANISM_LENGTH] {
    #[cfg(feature = "noise_xx")]
    if self.use_noise_xx {
      let can_propose_noise = if is_handler_server_role {
        self.noise_xx_local_sk_bytes_for_engine.is_some()
      } else {
        self.noise_xx_local_sk_bytes_for_engine.is_some()
          && self.noise_xx_remote_pk_bytes_for_engine.is_some()
      };
      if can_propose_noise {
        return NoiseXxMechanism::NAME_BYTES;
      } else {
        warn!(
          "NoiseXX configured (use_noise_xx=true) but required keys missing for current role ('{}') to propose; falling back.",
          if is_handler_server_role {
            "server"
          } else {
            "client"
          }
        );
      }
    }

    #[cfg(feature = "curve")]
    if self.use_curve {
      // CURVE has higher priority than PLAIN
      return crate::security::CurveMechanism::NAME_BYTES;
    }

    if self.use_plain {
      return PlainMechanism::NAME_BYTES;
    }
    NullMechanism::NAME_BYTES
  }
}