asupersync 0.3.4

Spec-first, cancel-correct, capability-secure async runtime for Rust.
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
//! Protocol adapters for external messaging ecosystems.
//!
//! This module provides a small, capability-aware contract for protocol
//! adapters that need to negotiate capabilities, serialize outbound frames,
//! decode inbound frames, and report lifecycle/health state without pulling
//! ambient runtime assumptions into the adapter layer.

use crate::cx::Cx;
use crate::messaging::redis::{RedisProtocolLimits, RespValue};

/// Error returned by protocol adapters.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProtocolAdapterError {
    /// The caller's capability context has already been cancelled.
    Cancelled,
    /// A lifecycle transition was requested from an invalid state.
    Lifecycle {
        /// Human-readable adapter name.
        adapter: &'static str,
        /// Description of the rejected lifecycle transition.
        detail: String,
    },
    /// Outbound serialization failed.
    Encode {
        /// Human-readable adapter name.
        adapter: &'static str,
        /// Error detail from the underlying encoder.
        detail: String,
    },
    /// Inbound frame decoding failed.
    Decode {
        /// Human-readable adapter name.
        adapter: &'static str,
        /// Error detail from the underlying decoder.
        detail: String,
    },
}

impl std::fmt::Display for ProtocolAdapterError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Cancelled => write!(f, "protocol adapter operation cancelled"),
            Self::Lifecycle { adapter, detail } => {
                write!(f, "{adapter} lifecycle error: {detail}")
            }
            Self::Encode { adapter, detail } => {
                write!(f, "{adapter} encode error: {detail}")
            }
            Self::Decode { adapter, detail } => {
                write!(f, "{adapter} decode error: {detail}")
            }
        }
    }
}

impl std::error::Error for ProtocolAdapterError {}

/// Connection lifecycle state for a protocol adapter.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProtocolConnectionState {
    /// No transport has been attached yet.
    Idle,
    /// The adapter can exchange application frames.
    Ready,
    /// The adapter is draining in-flight work before close.
    Draining,
    /// The transport is closed and the adapter cannot be reused.
    Closed,
}

/// Transport lifecycle events that an adapter must react to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProtocolTransportEvent {
    /// The underlying transport is now connected and writable.
    Connected,
    /// The caller requested a graceful drain before close.
    DrainRequested,
    /// The transport closed cleanly.
    Closed,
    /// The transport reset abruptly.
    Reset,
}

/// Stable capability summary published during protocol negotiation.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ProtocolCapabilities {
    /// Whether the protocol can safely carry multiple outstanding requests.
    pub pipelined_requests: bool,
    /// Whether the protocol has a natural request/reply model.
    pub request_reply: bool,
    /// Whether the protocol naturally supports streaming deliveries.
    pub streaming_publish: bool,
    /// Additional named features supported by the adapter.
    pub features: Vec<&'static str>,
}

/// Result of a protocol capability exchange.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProtocolNegotiation {
    /// Human-readable adapter name.
    pub adapter_name: &'static str,
    /// Protocol family this adapter speaks.
    pub protocol_family: &'static str,
    /// Optional version or dialect hint.
    pub version_hint: Option<&'static str>,
    /// Capabilities advertised by the adapter.
    pub capabilities: ProtocolCapabilities,
}

/// Adapter health snapshot.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProtocolHealth {
    /// Current lifecycle state.
    pub state: ProtocolConnectionState,
    /// Whether the adapter is ready to exchange application frames.
    pub ready: bool,
    /// Short lifecycle explanation.
    pub detail: &'static str,
}

/// Successfully decoded protocol frame.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DecodedProtocolMessage<M> {
    /// Decoded application/protocol message.
    pub message: M,
    /// Number of input bytes consumed to decode the frame.
    pub consumed: usize,
}

/// Common contract for protocol adapters.
pub trait ProtocolAdapter: Send + Sync + 'static {
    /// Application or wire-frame type produced by the adapter.
    type Message: Clone + Send + Sync + 'static;

    /// Human-readable adapter name.
    fn adapter_name(&self) -> &'static str;

    /// Protocol family identifier.
    fn protocol_family(&self) -> &'static str;

    /// Current connection lifecycle state.
    fn connection_state(&self) -> ProtocolConnectionState;

    /// Run protocol negotiation / capability exchange.
    fn begin_handshake(&self, cx: &Cx) -> Result<ProtocolNegotiation, ProtocolAdapterError>;

    /// Report stable adapter capabilities.
    fn capabilities(&self) -> ProtocolCapabilities;

    /// Encode a message into the supplied output buffer.
    fn encode_message(
        &self,
        message: &Self::Message,
        out: &mut Vec<u8>,
    ) -> Result<(), ProtocolAdapterError>;

    /// Attempt to decode one message from the provided bytes.
    ///
    /// Returns `Ok(None)` when more bytes are required.
    fn try_decode_message(
        &self,
        input: &[u8],
    ) -> Result<Option<DecodedProtocolMessage<Self::Message>>, ProtocolAdapterError>;

    /// Apply a transport lifecycle event.
    fn on_transport_event(
        &mut self,
        cx: &Cx,
        event: ProtocolTransportEvent,
    ) -> Result<ProtocolConnectionState, ProtocolAdapterError>;

    /// Return a health summary for the adapter.
    fn health_check(&self, cx: &Cx) -> Result<ProtocolHealth, ProtocolAdapterError>;
}

/// RESP protocol adapter backed by the existing Redis wire types.
#[derive(Debug, Clone)]
pub struct RespProtocolAdapter {
    limits: RedisProtocolLimits,
    state: ProtocolConnectionState,
}

impl RespProtocolAdapter {
    /// Create a RESP adapter using the provided decoder limits.
    #[must_use]
    pub fn new(limits: RedisProtocolLimits) -> Self {
        Self {
            limits,
            state: ProtocolConnectionState::Idle,
        }
    }

    /// Return the protocol limits used by this adapter.
    #[must_use]
    pub const fn limits(&self) -> RedisProtocolLimits {
        self.limits
    }
}

impl Default for RespProtocolAdapter {
    fn default() -> Self {
        Self::new(RedisProtocolLimits::default())
    }
}

impl ProtocolAdapter for RespProtocolAdapter {
    type Message = RespValue;

    fn adapter_name(&self) -> &'static str {
        "redis-resp-adapter"
    }

    fn protocol_family(&self) -> &'static str {
        "redis-resp"
    }

    fn connection_state(&self) -> ProtocolConnectionState {
        self.state
    }

    fn begin_handshake(&self, cx: &Cx) -> Result<ProtocolNegotiation, ProtocolAdapterError> {
        cx.checkpoint()
            .map_err(|_| ProtocolAdapterError::Cancelled)?;
        if self.state == ProtocolConnectionState::Closed {
            return Err(ProtocolAdapterError::Lifecycle {
                adapter: self.adapter_name(),
                detail: "cannot negotiate after transport close".to_string(),
            });
        }

        Ok(ProtocolNegotiation {
            adapter_name: self.adapter_name(),
            protocol_family: self.protocol_family(),
            version_hint: Some("RESP2"),
            capabilities: self.capabilities(),
        })
    }

    fn capabilities(&self) -> ProtocolCapabilities {
        ProtocolCapabilities {
            pipelined_requests: true,
            request_reply: true,
            streaming_publish: false,
            features: vec![
                "bulk_strings",
                "arrays",
                "integers",
                "simple_strings",
                "error_frames",
            ],
        }
    }

    fn encode_message(
        &self,
        message: &Self::Message,
        out: &mut Vec<u8>,
    ) -> Result<(), ProtocolAdapterError> {
        if self.state == ProtocolConnectionState::Closed {
            return Err(ProtocolAdapterError::Lifecycle {
                adapter: self.adapter_name(),
                detail: "cannot encode after transport close".to_string(),
            });
        }
        message.encode_into(out);
        Ok(())
    }

    fn try_decode_message(
        &self,
        input: &[u8],
    ) -> Result<Option<DecodedProtocolMessage<Self::Message>>, ProtocolAdapterError> {
        if self.state == ProtocolConnectionState::Closed {
            return Err(ProtocolAdapterError::Lifecycle {
                adapter: self.adapter_name(),
                detail: "cannot decode after transport close".to_string(),
            });
        }

        RespValue::try_decode_with_limits(input, &self.limits)
            .map(|decoded| {
                decoded.map(|(message, consumed)| DecodedProtocolMessage { message, consumed })
            })
            .map_err(|err| ProtocolAdapterError::Decode {
                adapter: self.adapter_name(),
                detail: err.to_string(),
            })
    }

    fn on_transport_event(
        &mut self,
        cx: &Cx,
        event: ProtocolTransportEvent,
    ) -> Result<ProtocolConnectionState, ProtocolAdapterError> {
        cx.checkpoint()
            .map_err(|_| ProtocolAdapterError::Cancelled)?;

        let next = match (self.state, event) {
            (ProtocolConnectionState::Idle, ProtocolTransportEvent::Connected) => {
                ProtocolConnectionState::Ready
            }
            (
                ProtocolConnectionState::Idle
                | ProtocolConnectionState::Ready
                | ProtocolConnectionState::Draining,
                ProtocolTransportEvent::Closed | ProtocolTransportEvent::Reset,
            ) => ProtocolConnectionState::Closed,
            (ProtocolConnectionState::Ready, ProtocolTransportEvent::DrainRequested) => {
                ProtocolConnectionState::Draining
            }
            (ProtocolConnectionState::Closed, _) => {
                return Err(ProtocolAdapterError::Lifecycle {
                    adapter: self.adapter_name(),
                    detail: "adapter is already closed".to_string(),
                });
            }
            _ => {
                return Err(ProtocolAdapterError::Lifecycle {
                    adapter: self.adapter_name(),
                    detail: format!("event {event:?} is invalid from state {:?}", self.state),
                });
            }
        };

        self.state = next;
        Ok(self.state)
    }

    fn health_check(&self, cx: &Cx) -> Result<ProtocolHealth, ProtocolAdapterError> {
        cx.checkpoint()
            .map_err(|_| ProtocolAdapterError::Cancelled)?;

        let detail = match self.state {
            ProtocolConnectionState::Idle => "waiting for transport connect",
            ProtocolConnectionState::Ready => "adapter ready",
            ProtocolConnectionState::Draining => "draining in-flight work",
            ProtocolConnectionState::Closed => "transport closed",
        };

        Ok(ProtocolHealth {
            state: self.state,
            ready: self.state == ProtocolConnectionState::Ready,
            detail,
        })
    }
}

#[cfg(test)]
mod tests {
    #![allow(
        clippy::pedantic,
        clippy::nursery,
        clippy::expect_fun_call,
        clippy::map_unwrap_or,
        clippy::cast_possible_wrap,
        clippy::future_not_send
    )]
    use super::{
        ProtocolAdapter, ProtocolAdapterError, ProtocolConnectionState, ProtocolTransportEvent,
        RespProtocolAdapter,
    };
    use crate::cx::Cx;
    use crate::messaging::redis::{RedisProtocolLimits, RespValue};
    use crate::types::{Budget, RegionId, TaskId};

    fn test_cx(slot: u32) -> Cx {
        Cx::new(
            RegionId::new_for_test(slot, 0),
            TaskId::new_for_test(slot, 0),
            Budget::INFINITE,
        )
    }

    #[test]
    fn resp_adapter_reports_handshake_capabilities() {
        let cx = test_cx(1);
        let adapter = RespProtocolAdapter::default();

        let negotiation = adapter.begin_handshake(&cx).expect("handshake succeeds");

        assert_eq!(negotiation.adapter_name, "redis-resp-adapter");
        assert_eq!(negotiation.protocol_family, "redis-resp");
        assert_eq!(negotiation.version_hint, Some("RESP2"));
        assert!(negotiation.capabilities.pipelined_requests);
        assert!(negotiation.capabilities.request_reply);
        assert!(negotiation.capabilities.features.contains(&"bulk_strings"));
    }

    #[test]
    fn resp_adapter_round_trips_resp_frames() {
        let adapter = RespProtocolAdapter::default();
        let frame = RespValue::Array(Some(vec![
            RespValue::BulkString(Some(b"PING".to_vec())),
            RespValue::BulkString(Some(b"payload".to_vec())),
        ]));

        let mut encoded = Vec::new();
        adapter
            .encode_message(&frame, &mut encoded)
            .expect("encode succeeds");

        let decoded = adapter
            .try_decode_message(&encoded)
            .expect("decode succeeds")
            .expect("full frame available");

        assert_eq!(decoded.message, frame);
        assert_eq!(decoded.consumed, encoded.len());
    }

    #[test]
    fn resp_adapter_encode_is_append_stable_for_prefilled_buffers() {
        let adapter = RespProtocolAdapter::default();
        let frame = RespValue::Array(Some(vec![
            RespValue::BulkString(Some(b"ECHO".to_vec())),
            RespValue::BulkString(Some(b"prefixed".to_vec())),
        ]));

        let mut standalone = Vec::new();
        adapter
            .encode_message(&frame, &mut standalone)
            .expect("standalone encode succeeds");

        let prefix = b"connection-buffer-prefix:";
        let mut prefilled = prefix.to_vec();
        adapter
            .encode_message(&frame, &mut prefilled)
            .expect("prefilled encode succeeds");

        assert_eq!(&prefilled[..prefix.len()], prefix);
        assert_eq!(&prefilled[prefix.len()..], standalone.as_slice());

        let decoded = adapter
            .try_decode_message(&prefilled[prefix.len()..])
            .expect("prefilled suffix decodes")
            .expect("full frame available");

        assert_eq!(decoded.message, frame);
        assert_eq!(decoded.consumed, standalone.len());
    }

    #[test]
    fn resp_adapter_decode_is_prefix_stable_under_pipelined_frames() {
        let adapter = RespProtocolAdapter::default();
        let first = RespValue::Array(Some(vec![
            RespValue::BulkString(Some(b"PING".to_vec())),
            RespValue::BulkString(Some(b"one".to_vec())),
        ]));
        let second = RespValue::Array(Some(vec![
            RespValue::BulkString(Some(b"ECHO".to_vec())),
            RespValue::BulkString(Some(b"two".to_vec())),
        ]));

        let mut first_frame = Vec::new();
        adapter
            .encode_message(&first, &mut first_frame)
            .expect("first frame encode succeeds");

        let mut second_frame = Vec::new();
        adapter
            .encode_message(&second, &mut second_frame)
            .expect("second frame encode succeeds");

        let baseline = adapter
            .try_decode_message(&first_frame)
            .expect("baseline decode succeeds")
            .expect("baseline frame available");

        let mut pipelined = first_frame.clone();
        pipelined.extend_from_slice(&second_frame);
        let pipelined_first = adapter
            .try_decode_message(&pipelined)
            .expect("pipelined decode succeeds")
            .expect("first pipelined frame available");

        assert_eq!(pipelined_first.message, baseline.message);
        assert_eq!(pipelined_first.consumed, first_frame.len());

        let pipelined_second = adapter
            .try_decode_message(&pipelined[pipelined_first.consumed..])
            .expect("second pipelined decode succeeds")
            .expect("second pipelined frame available");

        assert_eq!(pipelined_second.message, second);
        assert_eq!(pipelined_second.consumed, second_frame.len());
    }

    #[test]
    fn resp_adapter_decode_ignores_partial_trailing_frame() {
        let adapter = RespProtocolAdapter::default();
        let first = RespValue::Array(Some(vec![
            RespValue::BulkString(Some(b"SET".to_vec())),
            RespValue::BulkString(Some(b"key".to_vec())),
            RespValue::BulkString(Some(b"value".to_vec())),
        ]));

        let mut first_frame = Vec::new();
        adapter
            .encode_message(&first, &mut first_frame)
            .expect("first frame encode succeeds");
        let baseline = adapter
            .try_decode_message(&first_frame)
            .expect("baseline decode succeeds")
            .expect("baseline frame available");

        let mut with_partial_trailer = first_frame.clone();
        with_partial_trailer.extend_from_slice(b"$5\r\nhe");
        let decoded = adapter
            .try_decode_message(&with_partial_trailer)
            .expect("complete leading frame should decode")
            .expect("leading frame available");

        assert_eq!(decoded.message, baseline.message);
        assert_eq!(decoded.consumed, first_frame.len());
        assert_eq!(
            adapter
                .try_decode_message(&with_partial_trailer[decoded.consumed..])
                .expect("partial trailing frame is not a protocol error"),
            None
        );
    }

    #[test]
    fn resp_adapter_reports_partial_frames_without_consumption() {
        let adapter = RespProtocolAdapter::default();

        let decoded = adapter
            .try_decode_message(b"$5\r\nhe")
            .expect("partial frame should not be a protocol error");

        assert_eq!(decoded, None);
    }

    #[test]
    fn resp_adapter_enforces_configured_decode_limits() {
        let adapter = RespProtocolAdapter::new(RedisProtocolLimits::new().max_bulk_string_len(3));

        let err = adapter
            .try_decode_message(b"$4\r\nfour\r\n")
            .expect_err("oversized bulk string should surface as adapter decode error");

        assert!(matches!(
            err,
            ProtocolAdapterError::Decode { detail, .. }
                if detail.contains("bulk string length 4 exceeds maximum 3")
        ));
    }

    #[test]
    fn resp_adapter_tracks_lifecycle_and_health() {
        let cx = test_cx(2);
        let mut adapter = RespProtocolAdapter::default();

        assert_eq!(adapter.connection_state(), ProtocolConnectionState::Idle);
        assert_eq!(
            adapter.on_transport_event(&cx, ProtocolTransportEvent::Connected),
            Ok(ProtocolConnectionState::Ready)
        );
        assert!(adapter.health_check(&cx).expect("health").ready);
        assert_eq!(
            adapter.on_transport_event(&cx, ProtocolTransportEvent::DrainRequested),
            Ok(ProtocolConnectionState::Draining)
        );
        assert_eq!(
            adapter.on_transport_event(&cx, ProtocolTransportEvent::Closed),
            Ok(ProtocolConnectionState::Closed)
        );
        assert!(!adapter.health_check(&cx).expect("health").ready);
    }

    #[test]
    fn resp_adapter_rejects_reopen_after_close() {
        let cx = test_cx(3);
        let mut adapter = RespProtocolAdapter::default();
        adapter
            .on_transport_event(&cx, ProtocolTransportEvent::Closed)
            .expect("initial close succeeds");

        let err = adapter
            .on_transport_event(&cx, ProtocolTransportEvent::Connected)
            .expect_err("closed adapter should reject reconnect");

        assert!(matches!(err, ProtocolAdapterError::Lifecycle { .. }));
    }

    #[test]
    fn resp_adapter_reset_is_terminal_for_frame_operations() {
        let cx = test_cx(4);
        let mut adapter = RespProtocolAdapter::default();
        assert_eq!(
            adapter.on_transport_event(&cx, ProtocolTransportEvent::Reset),
            Ok(ProtocolConnectionState::Closed)
        );

        let handshake_err = adapter
            .begin_handshake(&cx)
            .expect_err("closed adapter should reject handshake");
        assert!(matches!(
            handshake_err,
            ProtocolAdapterError::Lifecycle { detail, .. }
                if detail.contains("cannot negotiate after transport close")
        ));

        let mut encoded = Vec::new();
        let encode_err = adapter
            .encode_message(&RespValue::SimpleString("PING".to_string()), &mut encoded)
            .expect_err("closed adapter should reject encode");
        assert!(matches!(
            encode_err,
            ProtocolAdapterError::Lifecycle { detail, .. }
                if detail.contains("cannot encode after transport close")
        ));
        assert!(encoded.is_empty());

        let decode_err = adapter
            .try_decode_message(b"+PONG\r\n")
            .expect_err("closed adapter should reject decode");
        assert!(matches!(
            decode_err,
            ProtocolAdapterError::Lifecycle { detail, .. }
                if detail.contains("cannot decode after transport close")
        ));

        let health = adapter.health_check(&cx).expect("closed health");
        assert_eq!(health.state, ProtocolConnectionState::Closed);
        assert!(!health.ready);
        assert_eq!(health.detail, "transport closed");
    }

    #[test]
    fn resp_adapter_observes_cancellation() {
        let cx = test_cx(5);
        cx.set_cancel_requested(true);

        let adapter = RespProtocolAdapter::default();
        let err = adapter
            .begin_handshake(&cx)
            .expect_err("cancelled cx should fail handshake");

        assert_eq!(err, ProtocolAdapterError::Cancelled);
    }
}