subc_client_rs/consumer/reservation.rs
1use super::*;
2
3/// A library-assigned wire correlation id, unique within its connection.
4pub type CorrelationId = u64;
5
6/// A request body validated before a caller-owned database transaction records
7/// the send and its correlation id.
8#[derive(Debug)]
9pub struct RequestBody(Frame);
10
11impl RequestBody {
12 /// Validate the body using the same size checks as an ordinary request.
13 pub fn new(body: Vec<u8>) -> Result<Self, CallError> {
14 Frame::build(
15 FrameType::Request,
16 Flags::new(false, Priority::Interactive, false),
17 0,
18 0,
19 0,
20 body,
21 )
22 .map(Self)
23 .map_err(CallError::from)
24 }
25}
26
27/// Route credit, writer capacity and a correlation id reserved for one request.
28///
29/// Dropping this value without calling [`Self::send`] sends nothing and releases
30/// both the route credit and the writer slot.
31#[must_use = "dropping a reservation releases it without sending"]
32pub struct RequestReservation {
33 writer: mpsc::OwnedPermit<WriteCommand>,
34 key: PendingKey,
35 reply: PendingReply,
36}
37
38impl RequestReservation {
39 /// The id already assigned to this request, also returned by [`Self::send`].
40 pub fn correlation_id(&self) -> CorrelationId {
41 self.key.corr
42 }
43
44 /// Synchronously hand the request to the connection's writer queue.
45 /// No reply polling or socket I/O happens here.
46 ///
47 /// Queued is not on the wire. If the connection fails after queuing, before
48 /// or after writing, `PendingReply` returns the same connection-loss errors
49 /// as [`SubcConsumer::request`]. A connection-loss error alone does not tell
50 /// you whether the module saw the request; include your own idempotency key
51 /// in the body for safe retries when the outcome is uncertain. If the route
52 /// closed since reservation, the writer skips the frame and the reply
53 /// returns the same closed-route error as an ordinary unwritten request.
54 ///
55 /// Only `opts.priority` and `opts.admission_class` apply to this already-open
56 /// route. The deadline supplied to [`SubcConsumer::reserve`] governs the
57 /// entire request, including the reply; `opts.timeout` does not replace it.
58 /// A non-`None` `opts.scope` is an argument error returned by the reply,
59 /// without queuing a frame. Select the scope when opening the route instead.
60 pub fn send(self, body: RequestBody, opts: CallOptions) -> (CorrelationId, PendingReply) {
61 if let Err(err) = opts.reject_scope() {
62 return (
63 self.key.corr,
64 PendingReply {
65 future: Box::pin(async move { Err(err) }),
66 },
67 );
68 }
69 let mut frame = body.0;
70 frame.header.channel = self.key.channel;
71 frame.header.epoch = self.key.epoch;
72 frame.header.corr = self.key.corr;
73 frame.header.flags =
74 Flags::new(false, opts.priority, false).with_admission_class(opts.admission_class);
75 self.writer.send(WriteCommand {
76 frame,
77 pending: Some(self.key),
78 });
79 (self.key.corr, self.reply)
80 }
81}
82
83/// The reply to a reserved request, with the same result as
84/// [`SubcConsumer::request`]. Dropping it stops waiting. On negotiated routes a
85/// written request keeps its credit until a wire terminal or route close. The
86/// writer skips a queued frame if its reply was dropped before dequeue, but
87/// dropping the reply cannot recall a frame already dequeued.
88#[must_use = "the reply must be awaited to observe the request outcome"]
89pub struct PendingReply {
90 future: Pin<Box<dyn Future<Output = Result<Vec<u8>, CallError>> + Send>>,
91}
92
93impl Future for PendingReply {
94 type Output = Result<Vec<u8>, CallError>;
95
96 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
97 self.future.as_mut().poll(cx)
98 }
99}
100
101impl SubcConsumer {
102 /// Reserve an ordinary request on an already-open route. A caller recording
103 /// sends in its own database (for example, SQLite) must await this method
104 /// before opening its transaction, so no write lock is held across a wait.
105 /// First validate the body with
106 /// [`RequestBody::new`], then await `reserve`, then call
107 /// [`RequestReservation::send`] inside the transaction without awaiting.
108 ///
109 /// Checks the route, waits for route credit and writer capacity, and assigns
110 /// a correlation id. `deadline` is an absolute Tokio deadline for reservation
111 /// and the eventual reply. No frame is queued until `send` is called.
112 pub async fn reserve(
113 &self,
114 route: &RouteHandle,
115 deadline: Instant,
116 ) -> Result<RequestReservation, CallError> {
117 let state = self.shared.route_state(*route)?;
118 let permit = state.acquire(false, deadline, None).await?;
119 let writer = self
120 .shared
121 .lock_inner()
122 .writer
123 .clone()
124 .ok_or_else(|| CallError::not_sent("subc connection is down before send"))?;
125 let writer = match timeout_at(deadline, writer.reserve_owned()).await {
126 Ok(Ok(writer)) => writer,
127 Ok(Err(_)) => return Err(CallError::not_sent("writer task closed before reservation")),
128 Err(_) => {
129 return Err(CallError::not_sent_with_cause(
130 "call deadline elapsed waiting for writer capacity",
131 NotSentCause::WriterCapacity,
132 ));
133 }
134 };
135 if Instant::now() >= deadline {
136 return Err(CallError::not_sent(
137 "call deadline elapsed before request was sent",
138 ));
139 }
140 let (tx, rx) = oneshot::channel();
141 let (key, _) = self
142 .shared
143 .allocate_request(Some(*route), route.channel, route.epoch)?;
144 {
145 let mut inner = self.shared.lock_inner();
146 if inner.closed || inner.generation != key.generation || inner.writer.is_none() {
147 return Err(CallError::not_sent(
148 "connection changed before request registration",
149 ));
150 }
151 if inner.route_epochs.get(&route.channel) != Some(route)
152 || inner.retired_routes.contains(route)
153 {
154 return Err(CallError::StaleRouteHandle(*route));
155 }
156 // Register before returning so route/connection teardown can settle
157 // the reply even when it races the later synchronous queue handoff.
158 let mut entry = PendingEntry::unary(tx, false, None, None);
159 entry.send_deadline = Some(deadline);
160 inner.pending.insert(key, entry);
161 if state.opted_in {
162 inner.wire_slots.insert(key, Arc::clone(&permit));
163 }
164 }
165 let registration = PendingRegistration::new(Arc::clone(&self.shared), key, false);
166 let shared = Arc::clone(&self.shared);
167 let reply = PendingReply {
168 future: Box::pin(async move {
169 let _permit = permit;
170 match shared.wait_for_reply(registration, rx, deadline).await? {
171 TerminalFrame::Response { body, .. } => Ok(body),
172 TerminalFrame::StreamEnd => Ok(Vec::new()),
173 TerminalFrame::Error { body, flags }
174 if error_codes::is_route_busy_retryable(
175 flags,
176 &body.code,
177 state.opted_in,
178 ) =>
179 {
180 Err(busy_error(&body))
181 }
182 TerminalFrame::Error { body, .. } => Err(CallError::Module(body)),
183 }
184 }),
185 };
186 Ok(RequestReservation { writer, key, reply })
187 }
188}