rocketmq-transport 1.0.0

Bounded TCP/TLS transport for RocketMQ 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
// Copyright 2026 The RocketMQ Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Affine ownership of one deferred response.

use std::fmt;
use std::sync::Arc;

use tracing::Instrument;

use super::deferred_response::DeferredSystemCancellationReason;
use super::deferred_response::DeferredSystemCloseReason;
use super::deferred_response::DeferredTerminalReason;
use super::OriginalRequestIdentity;
use super::RemotingResponse;
use super::RequestControlView;
use super::RequestId;
use super::ResponseCompletionOutcome;
use super::ResponseReceipt;
use super::ResponseSink;
use super::ResponseState;
use super::ResponseStateOutcome;
use super::WriteProgress;
use crate::admission::AdmissionClass;
use crate::contract::TransportContractViolation;
use crate::request_ordering::RequestOrdering;
use crate::session_executor::DeferredResumeExecutor;
use crate::session_view::SessionId;
use crate::telemetry::TransportTelemetry;

/// Result of transferring a request's affine deferred response right.
#[must_use]
pub enum DeferredResponderOutcome {
    /// The deferred response right was transferred.
    Taken(DeferredResponder),
    /// One-way ingress can never produce a response.
    OneWayRequest,
    /// This transport path has no durable deferred response owner.
    Unavailable,
    /// The request already transferred its deferred response right.
    AlreadyTaken,
    /// The handler outcome already consumed the response contract.
    OutcomeCompleted,
}

/// Result of consuming a deferred response capability.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[must_use]
pub enum DeferredResponseOutcome {
    /// Canonical response delivery completed.
    Completed(ResponseReceipt),
    /// Another terminal operation already completed the response.
    AlreadyCompleted,
    /// The response deadline elapsed before writing.
    DeadlineExceeded,
    /// The request owner cancelled the response.
    Cancelled,
    /// The canonical response session closed.
    SessionClosed,
    /// The bounded response queue rejected the response.
    QueueSaturated,
}

/// Internal response result retaining the terminal winner needed by resume.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum DeferredResponseAttempt {
    Completed(ResponseReceipt),
    AlreadyCompleted {
        state: super::ResponseTerminalState,
        reason: Option<DeferredTerminalReason>,
    },
    DeadlineExceeded,
    Cancelled,
    SessionClosed,
    QueueSaturated,
}

impl DeferredResponseAttempt {
    const fn public_outcome(self) -> DeferredResponseOutcome {
        match self {
            Self::Completed(receipt) => DeferredResponseOutcome::Completed(receipt),
            Self::AlreadyCompleted { .. } => DeferredResponseOutcome::AlreadyCompleted,
            Self::DeadlineExceeded => DeferredResponseOutcome::DeadlineExceeded,
            Self::Cancelled => DeferredResponseOutcome::Cancelled,
            Self::SessionClosed => DeferredResponseOutcome::SessionClosed,
            Self::QueueSaturated => DeferredResponseOutcome::QueueSaturated,
        }
    }
}

/// Caller-owned reason for cancelling a deferred response capability.
///
/// Trusted owner, session, processor, and service lifecycle reasons are sealed
/// inside the transport and cannot be selected through this API.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum DeferredCancellationReason {
    /// The caller can prove that its response receiver was dropped.
    ReceiverDropped,
}

/// Trusted seed that retains the one canonical response sink and its composition telemetry.
pub(crate) struct DeferredResponseSeed {
    sink: ResponseSink,
    telemetry: TransportTelemetry,
    session_id: SessionId,
    control: RequestControlView,
    resume: Option<DeferredResumeContext>,
    session_cleanup: Option<super::DeferredSessionCleanupRegistration>,
    observation: Option<crate::telemetry::RequestObservation>,
}

#[derive(Clone)]
pub(crate) struct DeferredResumeContext {
    pub(crate) ordering: RequestOrdering,
    pub(crate) class: AdmissionClass,
    pub(crate) executor: DeferredResumeExecutor,
}

impl DeferredResponseSeed {
    pub(crate) const fn new(
        sink: ResponseSink,
        telemetry: TransportTelemetry,
        session_id: SessionId,
        control: RequestControlView,
    ) -> Self {
        Self {
            sink,
            telemetry,
            session_id,
            control,
            resume: None,
            session_cleanup: None,
            observation: None,
        }
    }

    pub(crate) fn with_resume_context(
        mut self,
        ordering: RequestOrdering,
        class: AdmissionClass,
        executor: DeferredResumeExecutor,
    ) -> Self {
        self.resume = Some(DeferredResumeContext {
            ordering,
            class,
            executor,
        });
        self
    }

    pub(crate) fn with_session_cleanup(mut self, session_cleanup: super::DeferredSessionCleanupRegistration) -> Self {
        self.session_cleanup = Some(session_cleanup);
        self
    }

    pub(crate) fn with_observation(mut self, observation: crate::telemetry::RequestObservation) -> Self {
        self.observation = Some(observation);
        self
    }

    pub(crate) fn into_responder(self, original: OriginalRequestIdentity) -> DeferredResponder {
        #[cfg(test)]
        {
            DEFERRED_STATE_ALLOCATIONS.with(|count| count.set(count.get() + 1));
            self.telemetry.record_deferred_state_construction();
        }
        let state = Arc::new(ResponseState::observed(self.telemetry, original.original_code()));
        DeferredResponder {
            original,
            sink: Some(self.sink),
            state,
            session_id: self.session_id,
            control: Box::new(self.control),
            resume: self.resume,
            session_cleanup: self.session_cleanup,
            observation: self.observation,
            active: true,
        }
    }
}

/// Affine capability to complete exactly one later response.
///
/// The capability exposes no channel, connection, session handle, cancellation
/// token, or arbitrary write API. Dropping it abandons only this response.
///
/// ```compile_fail
/// use rocketmq_transport::api::DeferredResponder;
///
/// fn responders_are_affine(responder: &DeferredResponder) {
///     let _: DeferredResponder = responder.clone();
/// }
/// ```
#[must_use]
pub struct DeferredResponder {
    original: OriginalRequestIdentity,
    sink: Option<ResponseSink>,
    state: Arc<ResponseState>,
    session_id: SessionId,
    control: Box<RequestControlView>,
    resume: Option<DeferredResumeContext>,
    session_cleanup: Option<super::DeferredSessionCleanupRegistration>,
    observation: Option<crate::telemetry::RequestObservation>,
    active: bool,
}

impl DeferredResponder {
    /// Returns the immutable process-local request identity.
    #[must_use]
    pub const fn request_id(&self) -> RequestId {
        self.original.request_id()
    }

    /// Returns the trusted session identity that owns this response.
    #[must_use]
    pub const fn session_id(&self) -> SessionId {
        self.session_id
    }

    /// Returns the exact non-response terminal reason selected so far.
    #[must_use]
    pub fn terminal_reason(&self) -> Option<DeferredTerminalReason> {
        self.state.terminal_reason()
    }

    pub(crate) fn register(&self) -> Result<ResponseStateOutcome, TransportContractViolation> {
        self.state.register()
    }

    pub(crate) fn claim(&self) -> Result<ResponseStateOutcome, TransportContractViolation> {
        self.state.claim()
    }

    pub(crate) const fn control(&self) -> &RequestControlView {
        &self.control
    }

    pub(crate) fn resume_context(&self) -> Option<&DeferredResumeContext> {
        self.resume.as_ref()
    }

    pub(crate) fn response_state(&self) -> &Arc<ResponseState> {
        &self.state
    }

    pub(crate) fn request_span(&self) -> tracing::Span {
        self.observation
            .as_ref()
            .map_or_else(tracing::Span::none, crate::telemetry::RequestObservation::span)
    }

    pub(crate) fn take_session_cleanup(&mut self) -> Option<super::DeferredSessionCleanupRegistration> {
        self.session_cleanup.take()
    }

    pub(crate) fn session_cleanup(&self) -> Option<super::DeferredSessionCleanupRegistration> {
        self.session_cleanup.clone()
    }

    pub(crate) fn cleanup_close_with_reason(
        &mut self,
        reason: DeferredSystemCloseReason,
    ) -> Result<ResponseStateOutcome, TransportContractViolation> {
        let result = self.state.close_with_reason(reason);
        self.active = false;
        if matches!(result, Ok(ResponseStateOutcome::Applied(()))) {
            if let Some(observation) = &self.observation {
                observation.complete_cancelled(reason.terminal_reason());
            }
        }
        result
    }

    pub(crate) fn cleanup_cancel_with_reason(
        &mut self,
        reason: DeferredSystemCancellationReason,
    ) -> Result<ResponseStateOutcome, TransportContractViolation> {
        let result = self.state.cancel_with_reason(reason);
        self.active = false;
        if matches!(result, Ok(ResponseStateOutcome::Applied(()))) {
            if let Some(observation) = &self.observation {
                observation.complete_cancelled(reason.terminal_reason());
            }
        }
        result
    }

    pub(crate) const fn original_opaque(&self) -> i32 {
        self.original.original_opaque()
    }

    pub(crate) fn close_with_reason(
        mut self,
        reason: DeferredSystemCloseReason,
    ) -> Result<ResponseStateOutcome, TransportContractViolation> {
        let result = self.state.close_with_reason(reason);
        self.active = false;
        if matches!(result, Ok(ResponseStateOutcome::Applied(()))) {
            if let Some(observation) = &self.observation {
                observation.complete_cancelled(reason.terminal_reason());
            }
        }
        result
    }

    pub(crate) fn cancel_with_system_reason(
        mut self,
        reason: DeferredSystemCancellationReason,
    ) -> Result<ResponseStateOutcome, TransportContractViolation> {
        let result = self.state.cancel_with_reason(reason);
        self.active = false;
        if matches!(result, Ok(ResponseStateOutcome::Applied(()))) {
            if let Some(observation) = &self.observation {
                observation.complete_cancelled(reason.terminal_reason());
            }
        }
        result
    }

    /// Binds and delivers one response through the request's canonical response sink.
    ///
    /// # Errors
    ///
    /// Returns a typed, redacted error for immutable binding, encoding, or
    /// transport failure. Lifecycle, deadline, and capacity rejections are
    /// returned as source-free outcomes.
    pub async fn respond(
        self,
        response: RemotingResponse,
    ) -> Result<DeferredResponseOutcome, crate::error::TransportError> {
        self.respond_internal(response)
            .await
            .map(DeferredResponseAttempt::public_outcome)
    }

    pub(super) async fn respond_internal(
        self,
        response: RemotingResponse,
    ) -> Result<DeferredResponseAttempt, crate::error::TransportError> {
        let span = self.request_span();
        self.respond_in_request_span(response).instrument(span).await
    }

    async fn respond_in_request_span(
        mut self,
        response: RemotingResponse,
    ) -> Result<DeferredResponseAttempt, crate::error::TransportError> {
        let response_code = response.response_code();
        let body_kind = response.body_kind();
        let write_started = std::time::Instant::now();
        let mut claim = match self.state.begin_sending() {
            Ok(ResponseStateOutcome::Applied(claim)) => claim,
            Ok(ResponseStateOutcome::AlreadyCompleted { state, reason }) => {
                return Ok(DeferredResponseAttempt::AlreadyCompleted { state, reason })
            }
            Err(error) => return Err(crate::error::TransportError::response(error)),
        };
        self.active = false;
        let bound = match response.bind(self.original) {
            Ok(bound) => bound,
            Err(source) => {
                if let Some(outcome) = finish_deferred_claim(claim.fail(WriteProgress::NotStarted))? {
                    return Ok(outcome);
                }
                if let Some(observation) = &self.observation {
                    observation.complete_failure_without_kind(
                        crate::runtime::processor::ResponseObservationMode::Deferred,
                        Some(response_code),
                        Some(body_kind),
                        Some(WriteProgress::NotStarted),
                    );
                }
                return Err(crate::error::TransportError::response(source));
            }
        };
        let sink = self.sink.take().ok_or_else(|| {
            crate::error::TransportError::response(TransportContractViolation::DeferredResponseInvalidTransition {
                operation: "take_sink",
                state: "sending",
            })
        })?;
        let result = sink.send_deferred_response(bound, &mut claim).await;
        match result {
            Ok(response_outcome) => {
                let progress = response_completion_progress(response_outcome);
                let claim_result = match response_outcome {
                    ResponseCompletionOutcome::Completed(_) => claim.complete(),
                    _ => claim.fail(progress),
                };
                if let Some(outcome) = finish_deferred_claim(claim_result)? {
                    return Ok(outcome);
                }
                if let Some(observation) = &self.observation {
                    match response_outcome {
                        ResponseCompletionOutcome::Completed(receipt) => observation.complete_reply(
                            crate::runtime::processor::ResponseObservationMode::Deferred,
                            response_code,
                            body_kind,
                            write_started.elapsed(),
                            Ok(receipt),
                        ),
                        outcome => observation.complete_reply(
                            crate::runtime::processor::ResponseObservationMode::Deferred,
                            response_code,
                            body_kind,
                            write_started.elapsed(),
                            Err((Some(outcome), Some(progress))),
                        ),
                    }
                }
                Ok(deferred_response_outcome(response_outcome))
            }
            Err(error) => {
                let progress = error.write_progress();
                if let Some(outcome) = finish_deferred_claim(claim.fail(progress))? {
                    return Ok(outcome);
                }
                if let Some(observation) = &self.observation {
                    observation.complete_reply(
                        crate::runtime::processor::ResponseObservationMode::Deferred,
                        response_code,
                        body_kind,
                        write_started.elapsed(),
                        Err((None, Some(progress))),
                    );
                }
                Err(crate::error::TransportError::response(error))
            }
        }
    }

    /// Cancels only this deferred response right.
    ///
    /// # Errors
    ///
    /// Returns a transport error only for an invalid nonterminal transition.
    /// A prior terminal winner is the source-free
    /// [`DeferredResponseOutcome::AlreadyCompleted`] outcome.
    pub fn cancel(mut self) -> Result<DeferredResponseOutcome, crate::error::TransportError> {
        let result = self.state.cancel();
        self.active = false;
        if matches!(result, Ok(ResponseStateOutcome::Applied(()))) {
            if let Some(observation) = &self.observation {
                observation.complete_cancelled(DeferredTerminalReason::Explicit);
            }
        }
        match result {
            Ok(ResponseStateOutcome::Applied(())) => Ok(DeferredResponseOutcome::Cancelled),
            Ok(ResponseStateOutcome::AlreadyCompleted { .. }) => Ok(DeferredResponseOutcome::AlreadyCompleted),
            Err(error) => Err(crate::error::TransportError::response(error)),
        }
    }

    /// Cancels this deferred response after the caller-owned receiver is dropped.
    ///
    /// This method does not cancel the request, session, or parent lifecycle.
    ///
    /// # Errors
    ///
    /// Returns a transport error only for an invalid nonterminal transition.
    /// A prior terminal winner is the source-free
    /// [`DeferredResponseOutcome::AlreadyCompleted`] outcome.
    pub fn cancel_with_reason(
        mut self,
        reason: DeferredCancellationReason,
    ) -> Result<DeferredResponseOutcome, crate::error::TransportError> {
        let result = match reason {
            DeferredCancellationReason::ReceiverDropped => self.state.cancel_receiver_dropped(),
        };
        self.active = false;
        if matches!(result, Ok(ResponseStateOutcome::Applied(()))) {
            if let Some(observation) = &self.observation {
                observation.complete_cancelled(DeferredTerminalReason::ReceiverDropped);
            }
        }
        match result {
            Ok(ResponseStateOutcome::Applied(())) => Ok(DeferredResponseOutcome::Cancelled),
            Ok(ResponseStateOutcome::AlreadyCompleted { .. }) => Ok(DeferredResponseOutcome::AlreadyCompleted),
            Err(error) => Err(crate::error::TransportError::response(error)),
        }
    }
}

fn finish_deferred_claim(
    result: Result<ResponseStateOutcome, TransportContractViolation>,
) -> Result<Option<DeferredResponseAttempt>, crate::error::TransportError> {
    match result {
        Ok(ResponseStateOutcome::Applied(())) => Ok(None),
        Ok(ResponseStateOutcome::AlreadyCompleted { state, reason }) => {
            Ok(Some(DeferredResponseAttempt::AlreadyCompleted { state, reason }))
        }
        Err(error) => Err(crate::error::TransportError::response(error)),
    }
}

const fn response_completion_progress(outcome: ResponseCompletionOutcome) -> WriteProgress {
    match outcome {
        ResponseCompletionOutcome::Completed(_)
        | ResponseCompletionOutcome::AlreadyCompleted(_)
        | ResponseCompletionOutcome::DeadlineExpired
        | ResponseCompletionOutcome::Cancelled
        | ResponseCompletionOutcome::SessionClosed
        | ResponseCompletionOutcome::QueueSaturated => WriteProgress::NotStarted,
    }
}

const fn deferred_response_outcome(outcome: ResponseCompletionOutcome) -> DeferredResponseAttempt {
    match outcome {
        ResponseCompletionOutcome::Completed(receipt) => DeferredResponseAttempt::Completed(receipt),
        ResponseCompletionOutcome::AlreadyCompleted(state) => {
            DeferredResponseAttempt::AlreadyCompleted { state, reason: None }
        }
        ResponseCompletionOutcome::DeadlineExpired => DeferredResponseAttempt::DeadlineExceeded,
        ResponseCompletionOutcome::Cancelled => DeferredResponseAttempt::Cancelled,
        ResponseCompletionOutcome::SessionClosed => DeferredResponseAttempt::SessionClosed,
        ResponseCompletionOutcome::QueueSaturated => DeferredResponseAttempt::QueueSaturated,
    }
}

impl fmt::Debug for DeferredResponder {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("DeferredResponder")
            .field("active", &self.active)
            .finish_non_exhaustive()
    }
}

impl Drop for DeferredResponder {
    fn drop(&mut self) {
        if self.active && self.state.cancel_abandoned().is_ok() {
            if let Some(observation) = &self.observation {
                observation.complete_cancelled(DeferredTerminalReason::Abandoned);
            }
        }
        self.active = false;
    }
}

#[cfg(test)]
thread_local! {
    static DEFERRED_STATE_ALLOCATIONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

#[cfg(test)]
pub(crate) fn deferred_state_allocations() -> usize {
    DEFERRED_STATE_ALLOCATIONS.with(std::cell::Cell::get)
}

#[cfg(test)]
#[path = "../../tests/unit/dispatch/deferred_responder.rs"]
mod tests;