/build/source/nativelink-util/src/proto_stream_utils.rs
Line | Count | Source |
1 | | // Copyright 2024 The NativeLink Authors. All rights reserved. |
2 | | // |
3 | | // Licensed under the Functional Source License, Version 1.1, Apache 2.0 Future License (the "License"); |
4 | | // you may not use this file except in compliance with the License. |
5 | | // You may obtain a copy of the License at |
6 | | // |
7 | | // See LICENSE file for details |
8 | | // |
9 | | // Unless required by applicable law or agreed to in writing, software |
10 | | // distributed under the License is distributed on an "AS IS" BASIS, |
11 | | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
12 | | // See the License for the specific language governing permissions and |
13 | | // limitations under the License. |
14 | | |
15 | | use core::fmt::Debug; |
16 | | use core::mem; |
17 | | use core::pin::Pin; |
18 | | use core::task::{Context, Poll}; |
19 | | use std::borrow::Cow; |
20 | | use std::sync::Arc; |
21 | | |
22 | | use futures::{Stream, StreamExt}; |
23 | | use nativelink_error::{Error, ResultExt, error_if, make_input_err}; |
24 | | use nativelink_proto::google::bytestream::{ReadResponse, WriteRequest}; |
25 | | use parking_lot::Mutex; |
26 | | use tonic::{Status, Streaming}; |
27 | | |
28 | | use crate::resource_info::ResourceInfo; |
29 | | |
30 | | pub struct WriteRequestStreamWrapper<T> { |
31 | | pub resource_info: ResourceInfo<'static>, |
32 | | pub bytes_received: usize, |
33 | | stream: T, |
34 | | first_msg: Option<WriteRequest>, |
35 | | pub write_finished: bool, |
36 | | } |
37 | | |
38 | | impl<T> Debug for WriteRequestStreamWrapper<T> { |
39 | 19 | fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { |
40 | 19 | f.debug_struct("WriteRequestStreamWrapper") |
41 | 19 | .field("resource_info", &self.resource_info) |
42 | 19 | .field("bytes_received", &self.bytes_received) |
43 | 19 | .field("first_msg", &self.first_msg) |
44 | 19 | .field("write_finished", &self.write_finished) |
45 | 19 | .finish() |
46 | 19 | } |
47 | | } |
48 | | |
49 | | impl<T, E> WriteRequestStreamWrapper<T> |
50 | | where |
51 | | T: Stream<Item = Result<WriteRequest, E>> + Unpin, |
52 | | E: Into<Error>, |
53 | | { |
54 | 45 | pub async fn from(mut stream: T) -> Result<Self, Error> { |
55 | 45 | let first_msg44 = stream |
56 | 45 | .next() |
57 | 45 | .await |
58 | 45 | .err_tip(|| "Error receiving first message in stream")?0 |
59 | 45 | .err_tip(|| "Expected WriteRequest struct in stream (from)")?1 ; |
60 | | |
61 | 44 | let resource_info = ResourceInfo::new(&first_msg.resource_name, true) |
62 | 44 | .err_tip(|| {0 |
63 | 0 | format!( |
64 | | "Could not extract resource info from first message of stream: {}", |
65 | | first_msg.resource_name |
66 | | ) |
67 | 0 | })? |
68 | 44 | .to_owned(); |
69 | | |
70 | 44 | Ok(Self { |
71 | 44 | resource_info, |
72 | 44 | bytes_received: 0, |
73 | 44 | stream, |
74 | 44 | first_msg: Some(first_msg), |
75 | 44 | write_finished: false, |
76 | 44 | }) |
77 | 45 | } |
78 | | |
79 | 53 | pub async fn next(&mut self) -> Option<Result<WriteRequest, Error>> { |
80 | 161 | futures::future::poll_fn53 (|cx| Pin::new(&mut *self).poll_next(cx)).await53 |
81 | 52 | } |
82 | | |
83 | 4 | pub const fn is_first_msg(&self) -> bool { |
84 | 4 | self.first_msg.is_some() |
85 | 4 | } |
86 | | |
87 | | /// Returns whether the first message has `finish_write` set to true. |
88 | | /// This indicates a single-shot upload where all data is in one message. |
89 | 20 | pub fn is_first_msg_complete(&self) -> bool { |
90 | 20 | self.first_msg.as_ref().is_some_and(|msg| msg.finish_write) |
91 | 20 | } |
92 | | |
93 | 90 | fn enforce_wire_size_matches_digest_size(&self) -> bool { |
94 | 32 | matches!( |
95 | 90 | self.resource_info.compressor.as_deref(), |
96 | 33 | None | Some("identity") |
97 | | ) |
98 | 90 | } |
99 | | } |
100 | | |
101 | | impl<T, E> Stream for WriteRequestStreamWrapper<T> |
102 | | where |
103 | | E: Into<Error>, |
104 | | T: Stream<Item = Result<WriteRequest, E>> + Unpin, |
105 | | { |
106 | | type Item = Result<WriteRequest, Error>; |
107 | | |
108 | 207 | fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { |
109 | | // If the stream said that the previous message was the last one, then |
110 | | // return a stream EOF (i.e. None). |
111 | 207 | if self.write_finished { |
112 | 10 | if self.enforce_wire_size_matches_digest_size() { |
113 | 0 | error_if!( |
114 | 7 | self.bytes_received != self.resource_info.expected_size, |
115 | | "Did not send enough data. Expected {}, but so far received {}", |
116 | 0 | self.resource_info.expected_size, |
117 | 0 | self.bytes_received |
118 | | ); |
119 | 3 | } |
120 | 10 | return Poll::Ready(None); |
121 | 197 | } |
122 | | |
123 | | // Gets the next message, this is either the cached first or a |
124 | | // subsequent message from the wrapped Stream. |
125 | 197 | let maybe_message84 = if let Some(first_msg42 ) = self.first_msg.take() { |
126 | 42 | Ok(first_msg) |
127 | | } else { |
128 | 155 | match Pin::new(&mut self.stream).poll_next(cx) { |
129 | 113 | Poll::Pending => return Poll::Pending, |
130 | 38 | Poll::Ready(Some(maybe_message)) => maybe_message |
131 | 38 | .err_tip(|| format!0 ("Stream error at byte {}", self.bytes_received0 )), |
132 | 4 | Poll::Ready(None) => Err(make_input_err!( |
133 | 4 | "Expected WriteRequest struct in stream (got None)" |
134 | 4 | )), |
135 | | } |
136 | | }; |
137 | | |
138 | | // If we successfully got a message, update our internal state with the |
139 | | // message meta data. |
140 | 84 | Poll::Ready(Some(maybe_message.and_then(|message| {80 |
141 | 80 | self.write_finished = message.finish_write; |
142 | 80 | self.bytes_received += message.data.len(); |
143 | | |
144 | | // Check that we haven't read past the expected end. |
145 | 80 | if self.enforce_wire_size_matches_digest_size() |
146 | 51 | && self.bytes_received > self.resource_info.expected_size |
147 | | { |
148 | 2 | Err(make_input_err!( |
149 | 2 | "Sent too much data. Expected {}, but so far received {}", |
150 | 2 | self.resource_info.expected_size, |
151 | 2 | self.bytes_received |
152 | 2 | )) |
153 | | } else { |
154 | 78 | Ok(message) |
155 | | } |
156 | 80 | }))) |
157 | 207 | } |
158 | | } |
159 | | |
160 | | /// Represents the state of the first response in a `FirstStream`. |
161 | | #[derive(Debug)] |
162 | | pub enum FirstResponseState { |
163 | | /// Contains an optional first response that hasn't been consumed yet. |
164 | | /// A `None` value indicates the first response was EOF. |
165 | | Unused(Option<ReadResponse>), |
166 | | /// Indicates the first response has been consumed and future reads should |
167 | | /// come from the underlying stream. |
168 | | Used, |
169 | | } |
170 | | |
171 | | /// This provides a buffer for the first response from GrpcStore.read in order |
172 | | /// to allow the first read to occur within the retry loop. That means that if |
173 | | /// the connection establishes fine, but reading the first byte of the file |
174 | | /// fails we have the ability to retry before returning to the caller. |
175 | | #[derive(Debug)] |
176 | | pub struct FirstStream { |
177 | | /// The current state of the first response. When in the `Unused` state, |
178 | | /// contains an optional response which could be `None` or an EOF. |
179 | | /// Once consumed, transitions to the `Used` state. |
180 | | state: FirstResponseState, |
181 | | /// The stream to get responses from after the first response is consumed. |
182 | | stream: Streaming<ReadResponse>, |
183 | | } |
184 | | |
185 | | impl FirstStream { |
186 | | /// Creates a new `FirstStream` with the given first response and underlying |
187 | | /// stream. |
188 | 14 | pub const fn new( |
189 | 14 | first_response: Option<ReadResponse>, |
190 | 14 | stream: Streaming<ReadResponse>, |
191 | 14 | ) -> Self { |
192 | 14 | Self { |
193 | 14 | state: FirstResponseState::Unused(first_response), |
194 | 14 | stream, |
195 | 14 | } |
196 | 14 | } |
197 | | } |
198 | | |
199 | | impl Stream for FirstStream { |
200 | | type Item = Result<ReadResponse, Status>; |
201 | | |
202 | 111 | fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { |
203 | 111 | match mem::replace(&mut self.state, FirstResponseState::Used) { |
204 | 14 | FirstResponseState::Unused(first_response) => Poll::Ready(first_response.map(Ok)), |
205 | 97 | FirstResponseState::Used => Pin::new(&mut self.stream).poll_next(cx), |
206 | | } |
207 | 111 | } |
208 | | } |
209 | | |
210 | | /// Largest `data` payload in a single `ByteStream` `WriteRequest`, kept under |
211 | | /// tonic's 4MiB default `max_decoding_message_size` with room to spare. |
212 | | pub const MAX_WRITE_REQUEST_DATA_BYTES: usize = 2 * 1024 * 1024; |
213 | | |
214 | | /// This structure wraps all of the information required to perform a write |
215 | | /// request on the `GrpcStore`. It stores the last message retrieved which allows |
216 | | /// the write to resume since the UUID allows upload resume at the server. |
217 | | #[derive(Debug)] |
218 | | pub struct WriteState<T, E> |
219 | | where |
220 | | T: Stream<Item = Result<WriteRequest, E>> + Unpin + Send + 'static, |
221 | | E: Into<Error> + 'static, |
222 | | { |
223 | | instance_name: String, |
224 | | read_stream_error: Option<Error>, |
225 | | read_stream: WriteRequestStreamWrapper<T>, |
226 | | // Tonic doesn't appear to report an error until it has taken two messages, |
227 | | // therefore we are required to buffer the last two messages. |
228 | | cached_messages: [Option<WriteRequest>; 2], |
229 | | // When resuming after an error, the previous messages are cloned into this |
230 | | // queue upfront to allow them to be served back. |
231 | | resume_queue: [Option<WriteRequest>; 2], |
232 | | // An optimisation to avoid having to manage resume_queue when it's empty. |
233 | | is_resumed: bool, |
234 | | // Remainder of an incoming frame too large to forward in one message. |
235 | | // Drained before the next frame is read so ordering is preserved. |
236 | | pending: Option<WriteRequest>, |
237 | | // When false, a partially-consumed stream never reports `can_resume()`: |
238 | | // uploads whose server-side protocol cannot accept a replay from a |
239 | | // nonzero offset (REAPI compressed-blobs writes) must fail fast instead |
240 | | // of burning retries on guaranteed-rejected resumes. A stream that has |
241 | | // not yet been consumed can always be retried from the start. |
242 | | resumable: bool, |
243 | | } |
244 | | |
245 | | impl<T, E> WriteState<T, E> |
246 | | where |
247 | | T: Stream<Item = Result<WriteRequest, E>> + Unpin + Send + 'static, |
248 | | E: Into<Error> + 'static, |
249 | | { |
250 | 11 | pub const fn new(instance_name: String, read_stream: WriteRequestStreamWrapper<T>) -> Self { |
251 | 11 | Self { |
252 | 11 | instance_name, |
253 | 11 | read_stream_error: None, |
254 | 11 | read_stream, |
255 | 11 | cached_messages: [None, None], |
256 | 11 | resume_queue: [None, None], |
257 | 11 | is_resumed: false, |
258 | 11 | pending: None, |
259 | 11 | resumable: true, |
260 | 11 | } |
261 | 11 | } |
262 | | |
263 | | /// Caps the payload of an outgoing message, stashing anything over the |
264 | | /// limit to be sent as the following message. |
265 | | /// |
266 | | /// A caller can hand us a whole blob in one frame, and forwarding that |
267 | | /// verbatim produces a message the receiver rejects at its 4MiB default. |
268 | | /// Only the final piece carries `finish_write`, and each piece advances |
269 | | /// `write_offset` by what came before it. |
270 | 34 | fn split_oversized(&mut self, mut message: WriteRequest) -> WriteRequest { |
271 | 34 | if message.data.len() <= MAX_WRITE_REQUEST_DATA_BYTES { |
272 | 32 | return message; |
273 | 2 | } |
274 | 2 | let rest = message.data.split_off(MAX_WRITE_REQUEST_DATA_BYTES); |
275 | 2 | let sent_len = i64::try_from(message.data.len()).unwrap_or(i64::MAX); |
276 | 2 | self.pending = Some(WriteRequest { |
277 | 2 | resource_name: message.resource_name.clone(), |
278 | 2 | write_offset: message.write_offset.saturating_add(sent_len), |
279 | 2 | finish_write: message.finish_write, |
280 | 2 | data: rest, |
281 | 2 | }); |
282 | 2 | message.finish_write = false; |
283 | 2 | message |
284 | 34 | } |
285 | | |
286 | | /// Marks this write as non-resumable: once the stream has been partially |
287 | | /// consumed, `can_resume()` reports false so the caller fails fast with |
288 | | /// the original error instead of replaying messages the server-side |
289 | | /// protocol is guaranteed to reject. Retrying an unconsumed stream from |
290 | | /// the start remains allowed. |
291 | 4 | pub const fn set_non_resumable(&mut self) { |
292 | 4 | self.resumable = false; |
293 | 4 | } |
294 | | |
295 | 34 | pub(crate) const fn is_resumable(&self) -> bool { |
296 | 34 | self.resumable |
297 | 34 | } |
298 | | |
299 | 20 | fn push_message(&mut self, message: WriteRequest) { |
300 | 20 | self.cached_messages.swap(0, 1); |
301 | 20 | self.cached_messages[0] = Some(message); |
302 | 20 | } |
303 | | |
304 | 48 | const fn resumed_message(&mut self) -> Option<WriteRequest> { |
305 | 48 | if self.is_resumed { |
306 | | // The resume_queue is a circular buffer, that we have to shift, |
307 | | // since its only got two elements its a trivial swap. |
308 | 0 | self.resume_queue.swap(0, 1); |
309 | 0 | let message = self.resume_queue[0].take(); |
310 | 0 | if message.is_none() { |
311 | 0 | self.is_resumed = false; |
312 | 0 | } |
313 | 0 | message |
314 | | } else { |
315 | 48 | None |
316 | | } |
317 | 48 | } |
318 | | |
319 | 4 | pub const fn can_resume(&self) -> bool { |
320 | 4 | self.read_stream_error.is_none() |
321 | 4 | && ((self.resumable && self.cached_messages[0]0 .is_some0 ()) |
322 | 4 | || self.read_stream.is_first_msg()) |
323 | 4 | } |
324 | | |
325 | 0 | pub fn resume(&mut self) { |
326 | 0 | self.resume_queue.clone_from(&self.cached_messages); |
327 | 0 | self.is_resumed = true; |
328 | 0 | } |
329 | | |
330 | 11 | pub const fn take_read_stream_error(&mut self) -> Option<Error> { |
331 | 11 | self.read_stream_error.take() |
332 | 11 | } |
333 | | } |
334 | | |
335 | | /// A wrapper around `WriteState` to allow it to be reclaimed from the underlying |
336 | | /// write call in the case of failure. |
337 | | #[derive(Debug)] |
338 | | pub struct WriteStateWrapper<T, E> |
339 | | where |
340 | | T: Stream<Item = Result<WriteRequest, E>> + Unpin + Send + 'static, |
341 | | E: Into<Error> + 'static, |
342 | | { |
343 | | shared_state: Arc<Mutex<WriteState<T, E>>>, |
344 | | } |
345 | | |
346 | | impl<T, E> WriteStateWrapper<T, E> |
347 | | where |
348 | | T: Stream<Item = Result<WriteRequest, E>> + Unpin + Send + 'static, |
349 | | E: Into<Error> + 'static, |
350 | | { |
351 | 11 | pub const fn new(shared_state: Arc<Mutex<WriteState<T, E>>>) -> Self { |
352 | 11 | Self { shared_state } |
353 | 11 | } |
354 | | } |
355 | | |
356 | | impl<T, E> Stream for WriteStateWrapper<T, E> |
357 | | where |
358 | | T: Stream<Item = Result<WriteRequest, E>> + Unpin + Send + 'static, |
359 | | E: Into<Error> + 'static, |
360 | | { |
361 | | type Item = WriteRequest; |
362 | | |
363 | 48 | fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { |
364 | | const IS_UPLOAD_TRUE: bool = true; |
365 | | |
366 | | // This should be an uncontended lock since write was called. |
367 | 48 | let mut local_state = self.shared_state.lock(); |
368 | | // If this is the first or second call after a failure and we have |
369 | | // cached messages, then use the cached write requests. |
370 | 48 | let cached_message = local_state.resumed_message(); |
371 | 48 | if cached_message.is_some() { |
372 | 0 | return Poll::Ready(cached_message); |
373 | 48 | } |
374 | | // Finish draining an oversized frame before reading the next one. |
375 | 48 | if let Some(pending2 ) = local_state.pending.take() { |
376 | 2 | let message = local_state.split_oversized(pending); |
377 | 2 | if local_state.is_resumable() { |
378 | 2 | local_state.push_message(message.clone()); |
379 | 2 | }0 |
380 | 2 | return Poll::Ready(Some(message)); |
381 | 46 | } |
382 | | // Read a new write request from the downstream. |
383 | 46 | let Poll::Ready(maybe_message42 ) = Pin::new(&mut local_state.read_stream).poll_next(cx) |
384 | | else { |
385 | 4 | return Poll::Pending; |
386 | | }; |
387 | | // Update the instance name in the write request and forward it on. |
388 | 42 | let result = match maybe_message32 { |
389 | 32 | Some(Ok(mut message)) => { |
390 | 32 | if !message.resource_name.is_empty() { |
391 | | // Replace the instance name in the resource name if it is |
392 | | // different from the instance name in the write state. |
393 | 30 | match ResourceInfo::new(&message.resource_name, IS_UPLOAD_TRUE) { |
394 | 30 | Ok(mut resource_name) => { |
395 | 30 | if resource_name.instance_name != local_state.instance_name { |
396 | 1 | resource_name.instance_name = |
397 | 1 | Cow::Borrowed(&local_state.instance_name); |
398 | 1 | message.resource_name = resource_name.to_string(IS_UPLOAD_TRUE); |
399 | 29 | } |
400 | | } |
401 | 0 | Err(err) => { |
402 | 0 | local_state.read_stream_error = Some(err); |
403 | 0 | return Poll::Ready(None); |
404 | | } |
405 | | } |
406 | 2 | } |
407 | 32 | let message = local_state.split_oversized(message); |
408 | | // Cache the last request in case there is an error to allow |
409 | | // the upload to be resumed. Non-resumable writes skip the |
410 | | // clone: cached messages would never be replayed. |
411 | 32 | if local_state.is_resumable() { |
412 | 18 | local_state.push_message(message.clone()); |
413 | 18 | }14 |
414 | 32 | Some(message) |
415 | | } |
416 | 0 | Some(Err(err)) => { |
417 | 0 | local_state.read_stream_error = Some(err); |
418 | 0 | None |
419 | | } |
420 | 10 | None => None, |
421 | | }; |
422 | 42 | Poll::Ready(result) |
423 | 48 | } |
424 | | } |