/build/source/nativelink-util/src/action_messages.rs
Line | Count | Source (jump to first uncovered line) |
1 | | // Copyright 2024 The NativeLink Authors. All rights reserved. |
2 | | // |
3 | | // Licensed under the Apache License, Version 2.0 (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 | | // http://www.apache.org/licenses/LICENSE-2.0 |
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 std::cmp::Ordering; |
16 | | use std::collections::HashMap; |
17 | | use std::convert::Into; |
18 | | use std::hash::Hash; |
19 | | use std::time::{Duration, SystemTime}; |
20 | | |
21 | | use nativelink_error::{error_if, make_input_err, Error, ResultExt}; |
22 | | use nativelink_metric::{ |
23 | | publish, MetricFieldData, MetricKind, MetricPublishKnownKindData, MetricsComponent, |
24 | | }; |
25 | | use nativelink_proto::build::bazel::remote::execution::v2::{ |
26 | | execution_stage, Action, ActionResult as ProtoActionResult, ExecuteOperationMetadata, |
27 | | ExecuteRequest, ExecuteResponse, ExecutedActionMetadata, FileNode, LogFile, OutputDirectory, |
28 | | OutputFile, OutputSymlink, SymlinkNode, |
29 | | }; |
30 | | use nativelink_proto::google::longrunning::operation::Result as LongRunningResult; |
31 | | use nativelink_proto::google::longrunning::Operation; |
32 | | use nativelink_proto::google::rpc::Status; |
33 | | use prost::bytes::Bytes; |
34 | | use prost::Message; |
35 | | use prost_types::Any; |
36 | | use serde::ser::Error as SerdeError; |
37 | | use serde::{Deserialize, Serialize}; |
38 | | use uuid::Uuid; |
39 | | |
40 | | use crate::common::{DigestInfo, HashMapExt, VecExt}; |
41 | | use crate::digest_hasher::DigestHasherFunc; |
42 | | |
43 | | /// Default priority remote execution jobs will get when not provided. |
44 | | pub const DEFAULT_EXECUTION_PRIORITY: i32 = 0; |
45 | | |
46 | | /// Exit code sent if there is an internal error. |
47 | | pub const INTERNAL_ERROR_EXIT_CODE: i32 = -178; |
48 | | |
49 | | /// Holds an id that is unique to the client for a requested operation. |
50 | 8 | #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] |
51 | | pub enum OperationId { |
52 | | Uuid(Uuid), |
53 | | String(String), |
54 | | } |
55 | | |
56 | | impl OperationId { |
57 | 1 | pub fn into_string(self) -> String { |
58 | 1 | match self { |
59 | 1 | Self::Uuid(uuid) => uuid.to_string(), |
60 | 0 | Self::String(name) => name, |
61 | | } |
62 | 1 | } |
63 | | } |
64 | | |
65 | | impl Default for OperationId { |
66 | 84 | fn default() -> Self { |
67 | 84 | Self::Uuid(Uuid::new_v4()) |
68 | 84 | } |
69 | | } |
70 | | |
71 | | impl std::fmt::Display for OperationId { |
72 | 60 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
73 | 60 | match self { |
74 | 53 | Self::Uuid(uuid) => uuid.fmt(f), |
75 | 7 | Self::String(name) => f.write_str(name), |
76 | | } |
77 | 60 | } |
78 | | } |
79 | | |
80 | | impl MetricsComponent for OperationId { |
81 | 0 | fn publish( |
82 | 0 | &self, |
83 | 0 | _kind: MetricKind, |
84 | 0 | _field_metadata: MetricFieldData, |
85 | 0 | ) -> Result<MetricPublishKnownKindData, nativelink_metric::Error> { |
86 | 0 | Ok(MetricPublishKnownKindData::String(self.to_string())) |
87 | 0 | } |
88 | | } |
89 | | |
90 | 0 | fn uuid_to_string(uuid: &Uuid) -> String { |
91 | 0 | uuid.hyphenated().to_string() |
92 | 0 | } |
93 | | |
94 | | impl From<&str> for OperationId { |
95 | 517 | fn from(value: &str) -> Self { |
96 | 517 | match Uuid::parse_str(value) { |
97 | 12 | Ok(uuid) => Self::Uuid(uuid), |
98 | 505 | Err(_) => Self::String(value.to_string()), |
99 | | } |
100 | 517 | } |
101 | | } |
102 | | |
103 | | impl From<String> for OperationId { |
104 | 8 | fn from(value: String) -> Self { |
105 | 8 | match Uuid::parse_str(&value) { |
106 | 8 | Ok(uuid) => Self::Uuid(uuid), |
107 | 0 | Err(_) => Self::String(value), |
108 | | } |
109 | 8 | } |
110 | | } |
111 | | |
112 | | impl TryFrom<Bytes> for OperationId { |
113 | | type Error = Error; |
114 | | |
115 | 0 | fn try_from(value: Bytes) -> Result<Self, Self::Error> { |
116 | 0 | // This is an optimized path to attempt to do the conversion in-place |
117 | 0 | // to avoid an extra allocation/copy. |
118 | 0 | match value.try_into_mut() { |
119 | | // We are the only reference to the Bytes, so we can convert it into a Vec<u8> |
120 | | // for free then convert the Vec<u8> to a String for free too. |
121 | 0 | Ok(value) => { |
122 | 0 | let value = String::from_utf8(value.into()).map_err(|e| { |
123 | 0 | make_input_err!( |
124 | 0 | "Failed to convert bytes to string in try_from<Bytes> for OperationId : {e:?}" |
125 | 0 | ) |
126 | 0 | })?; |
127 | 0 | Ok(Self::from(value)) |
128 | | } |
129 | | // We could not take ownership of the Bytes, so we may need to copy our data. |
130 | 0 | Err(value) => { |
131 | 0 | let value = std::str::from_utf8(&value).map_err(|e| { |
132 | 0 | make_input_err!( |
133 | 0 | "Failed to convert bytes to string in try_from<Bytes> for OperationId : {e:?}" |
134 | 0 | ) |
135 | 0 | })?; |
136 | 0 | Ok(Self::from(value)) |
137 | | } |
138 | | } |
139 | 0 | } |
140 | | } |
141 | | |
142 | | /// Unique id of worker. |
143 | 0 | #[derive(Default, Eq, PartialEq, Hash, Copy, Clone, Serialize, Deserialize)] |
144 | | pub struct WorkerId(pub Uuid); |
145 | | |
146 | | impl MetricsComponent for WorkerId { |
147 | 0 | fn publish( |
148 | 0 | &self, |
149 | 0 | _kind: MetricKind, |
150 | 0 | _field_metadata: MetricFieldData, |
151 | 0 | ) -> Result<MetricPublishKnownKindData, nativelink_metric::Error> { |
152 | 0 | Ok(MetricPublishKnownKindData::String(uuid_to_string(&self.0))) |
153 | 0 | } |
154 | | } |
155 | | |
156 | | impl std::fmt::Display for WorkerId { |
157 | 74 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
158 | 74 | let mut buf = Uuid::encode_buffer(); |
159 | 74 | let worker_id_str = self.0.hyphenated().encode_lower(&mut buf); |
160 | 74 | f.write_fmt(format_args!("{worker_id_str}")) |
161 | 74 | } |
162 | | } |
163 | | |
164 | | impl std::fmt::Debug for WorkerId { |
165 | 5 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
166 | 5 | std::fmt::Display::fmt(&self, f) |
167 | 5 | } |
168 | | } |
169 | | |
170 | | impl TryFrom<String> for WorkerId { |
171 | | type Error = Error; |
172 | 8 | fn try_from(s: String) -> Result<Self, Self::Error> { |
173 | 8 | match Uuid::parse_str(&s) { |
174 | 0 | Err(e) => Err(make_input_err!( |
175 | 0 | "Failed to convert string to WorkerId : {s} : {e:?}", |
176 | 0 | )), |
177 | 8 | Ok(my_uuid) => Ok(WorkerId(my_uuid)), |
178 | | } |
179 | 8 | } |
180 | | } |
181 | | |
182 | | /// Holds the information needed to uniquely identify an action |
183 | | /// and if it is cachable or not. |
184 | 4 | #[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)] |
185 | | pub enum ActionUniqueQualifier { |
186 | | /// The action is cachable. |
187 | | Cachable(ActionUniqueKey), |
188 | | /// The action is uncachable. |
189 | | Uncachable(ActionUniqueKey), |
190 | | } |
191 | | |
192 | | impl MetricsComponent for ActionUniqueQualifier { |
193 | 0 | fn publish( |
194 | 0 | &self, |
195 | 0 | _kind: MetricKind, |
196 | 0 | field_metadata: MetricFieldData, |
197 | 0 | ) -> Result<MetricPublishKnownKindData, nativelink_metric::Error> { |
198 | 0 | let (cachable, action) = match self { |
199 | 0 | Self::Cachable(action) => (true, action), |
200 | 0 | Self::Uncachable(action) => (false, action), |
201 | | }; |
202 | 0 | publish!( |
203 | 0 | cachable, |
204 | 0 | &cachable, |
205 | 0 | MetricKind::Default, |
206 | 0 | "If the action is cachable.", |
207 | 0 | "" |
208 | | ); |
209 | 0 | action.publish(MetricKind::Component, field_metadata)?; |
210 | 0 | Ok(MetricPublishKnownKindData::Component) |
211 | 0 | } |
212 | | } |
213 | | |
214 | | impl ActionUniqueQualifier { |
215 | | /// Get the instance_name of the action. |
216 | 0 | pub const fn instance_name(&self) -> &String { |
217 | 0 | match self { |
218 | 0 | Self::Cachable(action) | Self::Uncachable(action) => &action.instance_name, |
219 | 0 | } |
220 | 0 | } |
221 | | |
222 | | /// Get the digest function of the action. |
223 | 5 | pub const fn digest_function(&self) -> DigestHasherFunc { |
224 | 5 | match self { |
225 | 5 | Self::Cachable(action) | Self::Uncachable(action0 ) => action.digest_function, |
226 | 5 | } |
227 | 5 | } |
228 | | |
229 | | /// Get the digest of the action. |
230 | 114 | pub const fn digest(&self) -> DigestInfo { |
231 | 114 | match self { |
232 | 114 | Self::Cachable(action109 ) | Self::Uncachable(action5 ) => action.digest, |
233 | 114 | } |
234 | 114 | } |
235 | | } |
236 | | |
237 | | impl std::fmt::Display for ActionUniqueQualifier { |
238 | 3 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
239 | 3 | let (cachable, unique_key) = match self { |
240 | 3 | Self::Cachable(action) => (true, action), |
241 | 0 | Self::Uncachable(action) => (false, action), |
242 | | }; |
243 | 3 | f.write_fmt(format_args!( |
244 | 3 | // Note: We use underscores because it makes escaping easier |
245 | 3 | // for redis. |
246 | 3 | "{}_{}_{}_{}_{}", |
247 | 3 | unique_key.instance_name, |
248 | 3 | unique_key.digest_function, |
249 | 3 | unique_key.digest.packed_hash(), |
250 | 3 | unique_key.digest.size_bytes(), |
251 | 3 | if cachable { 'c' } else { 'u'0 }, Branch (251:16): [True: 3, False: 0]
Branch (251:16): [Folded - Ignored]
|
252 | | )) |
253 | 3 | } |
254 | | } |
255 | | |
256 | | /// This is a utility struct used to make it easier to match `ActionInfos` in a |
257 | | /// `HashMap` without needing to construct an entire `ActionInfo`. |
258 | 8 | #[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize, M0 etricsComponent0 )] |
259 | | pub struct ActionUniqueKey { |
260 | | /// Name of instance group this action belongs to. |
261 | | #[metric(help = "Name of instance group this action belongs to.")] |
262 | | pub instance_name: String, |
263 | | /// The digest function this action expects. |
264 | | #[metric(help = "The digest function this action expects.")] |
265 | | pub digest_function: DigestHasherFunc, |
266 | | /// Digest of the underlying `Action`. |
267 | | #[metric(help = "Digest of the underlying Action.")] |
268 | | pub digest: DigestInfo, |
269 | | } |
270 | | |
271 | | impl std::fmt::Display for ActionUniqueKey { |
272 | 0 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
273 | 0 | f.write_fmt(format_args!( |
274 | 0 | "{}/{}/{}", |
275 | 0 | self.instance_name, self.digest_function, self.digest, |
276 | 0 | )) |
277 | 0 | } |
278 | | } |
279 | | |
280 | | /// Information needed to execute an action. This struct is used over bazel's proto `Action` |
281 | | /// for simplicity and offers a `salt`, which is useful to ensure during hashing (for dicts) |
282 | | /// to ensure we never match against another `ActionInfo` (when a task should never be cached). |
283 | | /// This struct must be 100% compatible with `ExecuteRequest` struct in `remote_execution.proto` |
284 | | /// except for the salt field. |
285 | 18 | #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, M0 etricsComponent0 )] |
286 | | pub struct ActionInfo { |
287 | | /// Digest of the underlying `Command`. |
288 | | #[metric(help = "Digest of the underlying Command.")] |
289 | | pub command_digest: DigestInfo, |
290 | | /// Digest of the underlying `Directory`. |
291 | | #[metric(help = "Digest of the underlying Directory.")] |
292 | | pub input_root_digest: DigestInfo, |
293 | | /// Timeout of the action. |
294 | | #[metric(help = "Timeout of the action.")] |
295 | | pub timeout: Duration, |
296 | | /// The properties rules that must be applied when finding a worker that can run this action. |
297 | | #[metric(group = "platform_properties")] |
298 | | pub platform_properties: HashMap<String, String>, |
299 | | /// The priority of the action. Higher value means it should execute faster. |
300 | | #[metric(help = "The priority of the action. Higher value means it should execute faster.")] |
301 | | pub priority: i32, |
302 | | /// When this action started to be loaded from the CAS. |
303 | | #[metric(help = "When this action started to be loaded from the CAS.")] |
304 | | pub load_timestamp: SystemTime, |
305 | | /// When this action was created. |
306 | | #[metric(help = "When this action was created.")] |
307 | | pub insert_timestamp: SystemTime, |
308 | | /// Info used to uniquely identify this ActionInfo and if it is cachable. |
309 | | /// This is primarily used to join actions/operations together using this key. |
310 | | #[metric(help = "Info used to uniquely identify this ActionInfo and if it is cachable.")] |
311 | | pub unique_qualifier: ActionUniqueQualifier, |
312 | | } |
313 | | |
314 | | impl ActionInfo { |
315 | | #[inline] |
316 | 0 | pub const fn instance_name(&self) -> &String { |
317 | 0 | self.unique_qualifier.instance_name() |
318 | 0 | } |
319 | | |
320 | | /// Returns the underlying digest of the `Action`. |
321 | | #[inline] |
322 | 74 | pub const fn digest(&self) -> DigestInfo { |
323 | 74 | self.unique_qualifier.digest() |
324 | 74 | } |
325 | | |
326 | 7 | pub fn try_from_action_and_execute_request( |
327 | 7 | execute_request: ExecuteRequest, |
328 | 7 | action: Action, |
329 | 7 | load_timestamp: SystemTime, |
330 | 7 | queued_timestamp: SystemTime, |
331 | 7 | ) -> Result<Self, Error> { |
332 | 7 | let unique_key = ActionUniqueKey { |
333 | 7 | instance_name: execute_request.instance_name, |
334 | 7 | digest_function: DigestHasherFunc::try_from(execute_request.digest_function) |
335 | 7 | .err_tip(|| format!("Could not find digest_function in try_from_action_and_execute_request {:?}", execute_request.digest_function)0 )?0 , |
336 | 7 | digest: execute_request |
337 | 7 | .action_digest |
338 | 7 | .err_tip(|| "Expected action_digest to exist on ExecuteRequest"0 )?0 |
339 | 7 | .try_into()?0 , |
340 | | }; |
341 | 7 | let unique_qualifier = if execute_request.skip_cache_lookup { Branch (341:35): [True: 0, False: 7]
Branch (341:35): [Folded - Ignored]
|
342 | 0 | ActionUniqueQualifier::Uncachable(unique_key) |
343 | | } else { |
344 | 7 | ActionUniqueQualifier::Cachable(unique_key) |
345 | | }; |
346 | | |
347 | 7 | let proto_properties = action.platform.unwrap_or_default(); |
348 | 7 | let mut platform_properties = HashMap::with_capacity(proto_properties.properties.len()); |
349 | 7 | for property0 in proto_properties.properties { |
350 | 0 | platform_properties.insert(property.name, property.value); |
351 | 0 | } |
352 | | |
353 | | Ok(Self { |
354 | 7 | command_digest: action |
355 | 7 | .command_digest |
356 | 7 | .err_tip(|| "Expected command_digest to exist on Action"0 )?0 |
357 | 7 | .try_into()?0 , |
358 | 7 | input_root_digest: action |
359 | 7 | .input_root_digest |
360 | 7 | .err_tip(|| "Expected input_root_digest to exist on Action"0 )?0 |
361 | 7 | .try_into()?0 , |
362 | 7 | timeout: action |
363 | 7 | .timeout |
364 | 7 | .unwrap_or_default() |
365 | 7 | .try_into() |
366 | 7 | .map_err(|_| make_input_err!("Failed convert proto duration to system duration")0 )?0 , |
367 | 7 | platform_properties, |
368 | 7 | priority: execute_request |
369 | 7 | .execution_policy |
370 | 7 | .unwrap_or_default() |
371 | 7 | .priority, |
372 | 7 | load_timestamp, |
373 | 7 | insert_timestamp: queued_timestamp, |
374 | 7 | unique_qualifier, |
375 | | }) |
376 | 7 | } |
377 | | } |
378 | | |
379 | | impl From<&ActionInfo> for ExecuteRequest { |
380 | 32 | fn from(val: &ActionInfo) -> Self { |
381 | 32 | let digest = val.digest().into(); |
382 | 32 | let (skip_cache_lookup, unique_qualifier) = match &val.unique_qualifier { |
383 | 27 | ActionUniqueQualifier::Cachable(unique_qualifier) => (false, unique_qualifier), |
384 | 5 | ActionUniqueQualifier::Uncachable(unique_qualifier) => (true, unique_qualifier), |
385 | | }; |
386 | 32 | Self { |
387 | 32 | instance_name: unique_qualifier.instance_name.clone(), |
388 | 32 | action_digest: Some(digest), |
389 | 32 | skip_cache_lookup, |
390 | 32 | execution_policy: None, // Not used in the worker. |
391 | 32 | results_cache_policy: None, // Not used in the worker. |
392 | 32 | digest_function: unique_qualifier.digest_function.proto_digest_func().into(), |
393 | 32 | } |
394 | 32 | } |
395 | | } |
396 | | |
397 | | /// Simple utility struct to determine if a string is representing a full path or |
398 | | /// just the name of the file. |
399 | | /// This is in order to be able to reuse the same struct instead of building different |
400 | | /// structs when converting `FileInfo` -> {`OutputFile`, `FileNode`} and other similar |
401 | | /// structs. |
402 | 0 | #[derive(Eq, PartialEq, Debug, Clone, Serialize, Deserialize)] |
403 | | pub enum NameOrPath { |
404 | | Name(String), |
405 | | Path(String), |
406 | | } |
407 | | |
408 | | impl PartialOrd for NameOrPath { |
409 | 0 | fn partial_cmp(&self, other: &Self) -> Option<Ordering> { |
410 | 0 | Some(self.cmp(other)) |
411 | 0 | } |
412 | | } |
413 | | |
414 | | impl Ord for NameOrPath { |
415 | 0 | fn cmp(&self, other: &Self) -> Ordering { |
416 | 0 | let self_lexical_name = match self { |
417 | 0 | Self::Name(name) => name, |
418 | 0 | Self::Path(path) => path, |
419 | | }; |
420 | 0 | let other_lexical_name = match other { |
421 | 0 | Self::Name(name) => name, |
422 | 0 | Self::Path(path) => path, |
423 | | }; |
424 | 0 | self_lexical_name.cmp(other_lexical_name) |
425 | 0 | } |
426 | | } |
427 | | |
428 | | /// Represents an individual file and associated metadata. |
429 | | /// This struct must be 100% compatible with `OutputFile` and `FileNode` structs |
430 | | /// in `remote_execution.proto`. |
431 | 0 | #[derive(Eq, PartialEq, Debug, Clone, Serialize, Deserialize)] |
432 | | pub struct FileInfo { |
433 | | pub name_or_path: NameOrPath, |
434 | | pub digest: DigestInfo, |
435 | | pub is_executable: bool, |
436 | | } |
437 | | |
438 | | //TODO: Make this TryFrom. |
439 | | impl From<FileInfo> for FileNode { |
440 | 0 | fn from(val: FileInfo) -> Self { |
441 | 0 | let NameOrPath::Name(name) = val.name_or_path else { Branch (441:13): [True: 0, False: 0]
Branch (441:13): [Folded - Ignored]
|
442 | 0 | panic!("Cannot return a FileInfo that uses a NameOrPath::Path(), it must be a NameOrPath::Name()"); |
443 | | }; |
444 | 0 | Self { |
445 | 0 | name, |
446 | 0 | digest: Some((&val.digest).into()), |
447 | 0 | is_executable: val.is_executable, |
448 | 0 | node_properties: Option::default(), // Not supported. |
449 | 0 | } |
450 | 0 | } |
451 | | } |
452 | | |
453 | | impl TryFrom<OutputFile> for FileInfo { |
454 | | type Error = Error; |
455 | | |
456 | 2 | fn try_from(output_file: OutputFile) -> Result<Self, Error> { |
457 | 2 | Ok(Self { |
458 | 2 | name_or_path: NameOrPath::Path(output_file.path), |
459 | 2 | digest: output_file |
460 | 2 | .digest |
461 | 2 | .err_tip(|| "Expected digest to exist on OutputFile"0 )?0 |
462 | 2 | .try_into()?0 , |
463 | 2 | is_executable: output_file.is_executable, |
464 | | }) |
465 | 2 | } |
466 | | } |
467 | | |
468 | | //TODO: Make this TryFrom. |
469 | | impl From<FileInfo> for OutputFile { |
470 | 7 | fn from(val: FileInfo) -> Self { |
471 | 7 | let NameOrPath::Path(path) = val.name_or_path else { Branch (471:13): [True: 7, False: 0]
Branch (471:13): [Folded - Ignored]
|
472 | 0 | panic!("Cannot return a FileInfo that uses a NameOrPath::Name(), it must be a NameOrPath::Path()"); |
473 | | }; |
474 | 7 | Self { |
475 | 7 | path, |
476 | 7 | digest: Some((&val.digest).into()), |
477 | 7 | is_executable: val.is_executable, |
478 | 7 | contents: Bytes::default(), |
479 | 7 | node_properties: Option::default(), // Not supported. |
480 | 7 | } |
481 | 7 | } |
482 | | } |
483 | | |
484 | | /// Represents an individual symlink file and associated metadata. |
485 | | /// This struct must be 100% compatible with `SymlinkNode` and `OutputSymlink`. |
486 | 0 | #[derive(Eq, PartialEq, Debug, Clone, Serialize, Deserialize)] |
487 | | pub struct SymlinkInfo { |
488 | | pub name_or_path: NameOrPath, |
489 | | pub target: String, |
490 | | } |
491 | | |
492 | | impl TryFrom<SymlinkNode> for SymlinkInfo { |
493 | | type Error = Error; |
494 | | |
495 | 0 | fn try_from(symlink_node: SymlinkNode) -> Result<Self, Error> { |
496 | 0 | Ok(Self { |
497 | 0 | name_or_path: NameOrPath::Name(symlink_node.name), |
498 | 0 | target: symlink_node.target, |
499 | 0 | }) |
500 | 0 | } |
501 | | } |
502 | | |
503 | | // TODO: Make this TryFrom. |
504 | | impl From<SymlinkInfo> for SymlinkNode { |
505 | 0 | fn from(val: SymlinkInfo) -> Self { |
506 | 0 | let NameOrPath::Name(name) = val.name_or_path else { Branch (506:13): [True: 0, False: 0]
Branch (506:13): [Folded - Ignored]
|
507 | 0 | panic!("Cannot return a SymlinkInfo that uses a NameOrPath::Path(), it must be a NameOrPath::Name()"); |
508 | | }; |
509 | 0 | Self { |
510 | 0 | name, |
511 | 0 | target: val.target, |
512 | 0 | node_properties: Option::default(), // Not supported. |
513 | 0 | } |
514 | 0 | } |
515 | | } |
516 | | |
517 | | impl TryFrom<OutputSymlink> for SymlinkInfo { |
518 | | type Error = Error; |
519 | | |
520 | 2 | fn try_from(output_symlink: OutputSymlink) -> Result<Self, Error> { |
521 | 2 | Ok(Self { |
522 | 2 | name_or_path: NameOrPath::Path(output_symlink.path), |
523 | 2 | target: output_symlink.target, |
524 | 2 | }) |
525 | 2 | } |
526 | | } |
527 | | |
528 | | // TODO: Make this TryFrom. |
529 | | impl From<SymlinkInfo> for OutputSymlink { |
530 | 2 | fn from(val: SymlinkInfo) -> Self { |
531 | 2 | let NameOrPath::Path(path) = val.name_or_path else { Branch (531:13): [True: 2, False: 0]
Branch (531:13): [Folded - Ignored]
|
532 | 0 | panic!("Cannot return a SymlinkInfo that uses a NameOrPath::Path(), it must be a NameOrPath::Name()"); |
533 | | }; |
534 | 2 | Self { |
535 | 2 | path, |
536 | 2 | target: val.target, |
537 | 2 | node_properties: Option::default(), // Not supported. |
538 | 2 | } |
539 | 2 | } |
540 | | } |
541 | | |
542 | | /// Represents an individual directory file and associated metadata. |
543 | | /// This struct must be 100% compatible with `SymlinkNode` and `OutputSymlink`. |
544 | 0 | #[derive(Eq, PartialEq, Debug, Clone, Serialize, Deserialize)] |
545 | | pub struct DirectoryInfo { |
546 | | pub path: String, |
547 | | pub tree_digest: DigestInfo, |
548 | | } |
549 | | |
550 | | impl TryFrom<OutputDirectory> for DirectoryInfo { |
551 | | type Error = Error; |
552 | | |
553 | 2 | fn try_from(output_directory: OutputDirectory) -> Result<Self, Error> { |
554 | 2 | Ok(Self { |
555 | 2 | path: output_directory.path, |
556 | 2 | tree_digest: output_directory |
557 | 2 | .tree_digest |
558 | 2 | .err_tip(|| "Expected tree_digest to exist in OutputDirectory"0 )?0 |
559 | 2 | .try_into()?0 , |
560 | | }) |
561 | 2 | } |
562 | | } |
563 | | |
564 | | impl From<DirectoryInfo> for OutputDirectory { |
565 | 1 | fn from(val: DirectoryInfo) -> Self { |
566 | 1 | Self { |
567 | 1 | path: val.path, |
568 | 1 | tree_digest: Some(val.tree_digest.into()), |
569 | 1 | is_topologically_sorted: false, |
570 | 1 | } |
571 | 1 | } |
572 | | } |
573 | | |
574 | | /// Represents the metadata associated with the execution result. |
575 | | /// This struct must be 100% compatible with `ExecutedActionMetadata`. |
576 | 0 | #[derive(Eq, PartialEq, Debug, Clone, Serialize, Deserialize)] |
577 | | pub struct ExecutionMetadata { |
578 | | pub worker: String, |
579 | | pub queued_timestamp: SystemTime, |
580 | | pub worker_start_timestamp: SystemTime, |
581 | | pub worker_completed_timestamp: SystemTime, |
582 | | pub input_fetch_start_timestamp: SystemTime, |
583 | | pub input_fetch_completed_timestamp: SystemTime, |
584 | | pub execution_start_timestamp: SystemTime, |
585 | | pub execution_completed_timestamp: SystemTime, |
586 | | pub output_upload_start_timestamp: SystemTime, |
587 | | pub output_upload_completed_timestamp: SystemTime, |
588 | | } |
589 | | |
590 | | impl Default for ExecutionMetadata { |
591 | 1 | fn default() -> Self { |
592 | 1 | Self { |
593 | 1 | worker: String::new(), |
594 | 1 | queued_timestamp: SystemTime::UNIX_EPOCH, |
595 | 1 | worker_start_timestamp: SystemTime::UNIX_EPOCH, |
596 | 1 | worker_completed_timestamp: SystemTime::UNIX_EPOCH, |
597 | 1 | input_fetch_start_timestamp: SystemTime::UNIX_EPOCH, |
598 | 1 | input_fetch_completed_timestamp: SystemTime::UNIX_EPOCH, |
599 | 1 | execution_start_timestamp: SystemTime::UNIX_EPOCH, |
600 | 1 | execution_completed_timestamp: SystemTime::UNIX_EPOCH, |
601 | 1 | output_upload_start_timestamp: SystemTime::UNIX_EPOCH, |
602 | 1 | output_upload_completed_timestamp: SystemTime::UNIX_EPOCH, |
603 | 1 | } |
604 | 1 | } |
605 | | } |
606 | | |
607 | | impl From<ExecutionMetadata> for ExecutedActionMetadata { |
608 | 17 | fn from(val: ExecutionMetadata) -> Self { |
609 | 17 | Self { |
610 | 17 | worker: val.worker, |
611 | 17 | queued_timestamp: Some(val.queued_timestamp.into()), |
612 | 17 | worker_start_timestamp: Some(val.worker_start_timestamp.into()), |
613 | 17 | worker_completed_timestamp: Some(val.worker_completed_timestamp.into()), |
614 | 17 | input_fetch_start_timestamp: Some(val.input_fetch_start_timestamp.into()), |
615 | 17 | input_fetch_completed_timestamp: Some(val.input_fetch_completed_timestamp.into()), |
616 | 17 | execution_start_timestamp: Some(val.execution_start_timestamp.into()), |
617 | 17 | execution_completed_timestamp: Some(val.execution_completed_timestamp.into()), |
618 | 17 | output_upload_start_timestamp: Some(val.output_upload_start_timestamp.into()), |
619 | 17 | output_upload_completed_timestamp: Some(val.output_upload_completed_timestamp.into()), |
620 | 17 | virtual_execution_duration: val |
621 | 17 | .execution_completed_timestamp |
622 | 17 | .duration_since(val.execution_start_timestamp) |
623 | 17 | .ok() |
624 | 17 | .and_then(|duration| prost_types::Duration::try_from(duration).ok()), |
625 | 17 | auxiliary_metadata: Vec::default(), |
626 | 17 | } |
627 | 17 | } |
628 | | } |
629 | | |
630 | | impl TryFrom<ExecutedActionMetadata> for ExecutionMetadata { |
631 | | type Error = Error; |
632 | | |
633 | 3 | fn try_from(eam: ExecutedActionMetadata) -> Result<Self, Error> { |
634 | 3 | Ok(Self { |
635 | 3 | worker: eam.worker, |
636 | 3 | queued_timestamp: eam |
637 | 3 | .queued_timestamp |
638 | 3 | .err_tip(|| "Expected queued_timestamp to exist in ExecutedActionMetadata"0 )?0 |
639 | 3 | .try_into()?0 , |
640 | 3 | worker_start_timestamp: eam |
641 | 3 | .worker_start_timestamp |
642 | 3 | .err_tip(|| "Expected worker_start_timestamp to exist in ExecutedActionMetadata"0 )?0 |
643 | 3 | .try_into()?0 , |
644 | 3 | worker_completed_timestamp: eam |
645 | 3 | .worker_completed_timestamp |
646 | 3 | .err_tip(|| { |
647 | 0 | "Expected worker_completed_timestamp to exist in ExecutedActionMetadata" |
648 | 3 | })?0 |
649 | 3 | .try_into()?0 , |
650 | 3 | input_fetch_start_timestamp: eam |
651 | 3 | .input_fetch_start_timestamp |
652 | 3 | .err_tip(|| { |
653 | 0 | "Expected input_fetch_start_timestamp to exist in ExecutedActionMetadata" |
654 | 3 | })?0 |
655 | 3 | .try_into()?0 , |
656 | 3 | input_fetch_completed_timestamp: eam |
657 | 3 | .input_fetch_completed_timestamp |
658 | 3 | .err_tip(|| { |
659 | 0 | "Expected input_fetch_completed_timestamp to exist in ExecutedActionMetadata" |
660 | 3 | })?0 |
661 | 3 | .try_into()?0 , |
662 | 3 | execution_start_timestamp: eam |
663 | 3 | .execution_start_timestamp |
664 | 3 | .err_tip(|| { |
665 | 0 | "Expected execution_start_timestamp to exist in ExecutedActionMetadata" |
666 | 3 | })?0 |
667 | 3 | .try_into()?0 , |
668 | 3 | execution_completed_timestamp: eam |
669 | 3 | .execution_completed_timestamp |
670 | 3 | .err_tip(|| { |
671 | 0 | "Expected execution_completed_timestamp to exist in ExecutedActionMetadata" |
672 | 3 | })?0 |
673 | 3 | .try_into()?0 , |
674 | 3 | output_upload_start_timestamp: eam |
675 | 3 | .output_upload_start_timestamp |
676 | 3 | .err_tip(|| { |
677 | 0 | "Expected output_upload_start_timestamp to exist in ExecutedActionMetadata" |
678 | 3 | })?0 |
679 | 3 | .try_into()?0 , |
680 | 3 | output_upload_completed_timestamp: eam |
681 | 3 | .output_upload_completed_timestamp |
682 | 3 | .err_tip(|| { |
683 | 0 | "Expected output_upload_completed_timestamp to exist in ExecutedActionMetadata" |
684 | 3 | })?0 |
685 | 3 | .try_into()?0 , |
686 | | }) |
687 | 3 | } |
688 | | } |
689 | | |
690 | | /// Represents the results of an execution. |
691 | | /// This struct must be 100% compatible with `ActionResult` in `remote_execution.proto`. |
692 | 0 | #[derive(Eq, PartialEq, Debug, Clone, Serialize, Deserialize)] |
693 | | pub struct ActionResult { |
694 | | pub output_files: Vec<FileInfo>, |
695 | | pub output_folders: Vec<DirectoryInfo>, |
696 | | pub output_directory_symlinks: Vec<SymlinkInfo>, |
697 | | pub output_file_symlinks: Vec<SymlinkInfo>, |
698 | | pub exit_code: i32, |
699 | | pub stdout_digest: DigestInfo, |
700 | | pub stderr_digest: DigestInfo, |
701 | | pub execution_metadata: ExecutionMetadata, |
702 | | pub server_logs: HashMap<String, DigestInfo>, |
703 | | pub error: Option<Error>, |
704 | | pub message: String, |
705 | | } |
706 | | |
707 | | impl Default for ActionResult { |
708 | 7 | fn default() -> Self { |
709 | 7 | ActionResult { |
710 | 7 | output_files: Default::default(), |
711 | 7 | output_folders: Default::default(), |
712 | 7 | output_directory_symlinks: Default::default(), |
713 | 7 | output_file_symlinks: Default::default(), |
714 | 7 | exit_code: INTERNAL_ERROR_EXIT_CODE, |
715 | 7 | stdout_digest: DigestInfo::new([0u8; 32], 0), |
716 | 7 | stderr_digest: DigestInfo::new([0u8; 32], 0), |
717 | 7 | execution_metadata: ExecutionMetadata { |
718 | 7 | worker: String::new(), |
719 | 7 | queued_timestamp: SystemTime::UNIX_EPOCH, |
720 | 7 | worker_start_timestamp: SystemTime::UNIX_EPOCH, |
721 | 7 | worker_completed_timestamp: SystemTime::UNIX_EPOCH, |
722 | 7 | input_fetch_start_timestamp: SystemTime::UNIX_EPOCH, |
723 | 7 | input_fetch_completed_timestamp: SystemTime::UNIX_EPOCH, |
724 | 7 | execution_start_timestamp: SystemTime::UNIX_EPOCH, |
725 | 7 | execution_completed_timestamp: SystemTime::UNIX_EPOCH, |
726 | 7 | output_upload_start_timestamp: SystemTime::UNIX_EPOCH, |
727 | 7 | output_upload_completed_timestamp: SystemTime::UNIX_EPOCH, |
728 | 7 | }, |
729 | 7 | server_logs: Default::default(), |
730 | 7 | error: None, |
731 | 7 | message: String::new(), |
732 | 7 | } |
733 | 7 | } |
734 | | } |
735 | | |
736 | | // TODO(allada) Remove the need for clippy argument by making the ActionResult and ProtoActionResult |
737 | | // a Box. |
738 | | /// The execution status/stage. This should match `ExecutionStage::Value` in `remote_execution.proto`. |
739 | 4 | #[derive(PartialEq, Debug, Clone, Serialize0 , Deserialize)] |
740 | | #[allow(clippy::large_enum_variant)] |
741 | | pub enum ActionStage { |
742 | | /// Stage is unknown. |
743 | | Unknown, |
744 | | /// Checking the cache to see if action exists. |
745 | | CacheCheck, |
746 | | /// Action has been accepted and waiting for worker to take it. |
747 | | Queued, |
748 | | // TODO(allada) We need a way to know if the job was sent to a worker, but hasn't begun |
749 | | // execution yet. |
750 | | /// Worker is executing the action. |
751 | | Executing, |
752 | | /// Worker completed the work with result. |
753 | | Completed(ActionResult), |
754 | | /// Result was found from cache, don't decode the proto just to re-encode it. |
755 | | #[serde(serialize_with = "serialize_proto_result", skip_deserializing)] |
756 | | // The serialization step decodes this to an ActionResult which is serializable. |
757 | | // Since it will always be serialized as an ActionResult, we do not need to support |
758 | | // deserialization on this type at all. |
759 | | // In theory, serializing this should never happen so performance shouldn't be affected. |
760 | | CompletedFromCache(ProtoActionResult), |
761 | | } |
762 | | |
763 | 0 | fn serialize_proto_result<S>(v: &ProtoActionResult, serializer: S) -> Result<S::Ok, S::Error> |
764 | 0 | where |
765 | 0 | S: serde::Serializer, |
766 | 0 | { |
767 | 0 | let s = ActionResult::try_from(v.clone()).map_err(S::Error::custom)?; |
768 | 0 | s.serialize(serializer) |
769 | 0 | } |
770 | | |
771 | | impl ActionStage { |
772 | 89 | pub const fn has_action_result(&self) -> bool { |
773 | 89 | match self { |
774 | 76 | Self::Unknown | Self::CacheCheck | Self::Queued | Self::Executing => false, |
775 | 13 | Self::Completed(_) | Self::CompletedFromCache(_) => true, |
776 | | } |
777 | 89 | } |
778 | | |
779 | | /// Returns true if the worker considers the action done and no longer needs to be tracked. |
780 | | // Note: This function is separate from `has_action_result()` to not mix the concept of |
781 | | // "finished" with "has a result". |
782 | 88 | pub const fn is_finished(&self) -> bool { |
783 | 88 | self.has_action_result() |
784 | 88 | } |
785 | | |
786 | | /// Returns if the stage enum is the same as the other stage enum, but |
787 | | /// does not compare the values of the enum. |
788 | 39 | pub const fn is_same_stage(&self, other: &Self) -> bool { |
789 | 39 | matches!( |
790 | 39 | (self, other), |
791 | | (Self::Unknown, Self::Unknown) |
792 | | | (Self::CacheCheck, Self::CacheCheck) |
793 | | | (Self::Queued, Self::Queued) |
794 | | | (Self::Executing, Self::Executing) |
795 | | | (Self::Completed(_), Self::Completed(_)) |
796 | | | (Self::CompletedFromCache(_), Self::CompletedFromCache(_)) |
797 | | ) |
798 | 39 | } |
799 | | } |
800 | | |
801 | | impl MetricsComponent for ActionStage { |
802 | 0 | fn publish( |
803 | 0 | &self, |
804 | 0 | _kind: MetricKind, |
805 | 0 | _field_metadata: MetricFieldData, |
806 | 0 | ) -> Result<MetricPublishKnownKindData, nativelink_metric::Error> { |
807 | 0 | let value = match self { |
808 | 0 | ActionStage::Unknown => "Unknown".to_string(), |
809 | 0 | ActionStage::CacheCheck => "CacheCheck".to_string(), |
810 | 0 | ActionStage::Queued => "Queued".to_string(), |
811 | 0 | ActionStage::Executing => "Executing".to_string(), |
812 | 0 | ActionStage::Completed(_) => "Completed".to_string(), |
813 | 0 | ActionStage::CompletedFromCache(_) => "CompletedFromCache".to_string(), |
814 | | }; |
815 | 0 | Ok(MetricPublishKnownKindData::String(value)) |
816 | 0 | } |
817 | | } |
818 | | |
819 | | impl From<&ActionStage> for execution_stage::Value { |
820 | 1 | fn from(val: &ActionStage) -> Self { |
821 | 1 | match val { |
822 | 0 | ActionStage::Unknown => Self::Unknown, |
823 | 0 | ActionStage::CacheCheck => Self::CacheCheck, |
824 | 0 | ActionStage::Queued => Self::Queued, |
825 | 0 | ActionStage::Executing => Self::Executing, |
826 | 1 | ActionStage::Completed(_) | ActionStage::CompletedFromCache(_) => Self::Completed, |
827 | | } |
828 | 1 | } |
829 | | } |
830 | | |
831 | 11 | pub fn to_execute_response(action_result: ActionResult) -> ExecuteResponse { |
832 | 11 | fn logs_from(server_logs: HashMap<String, DigestInfo>) -> HashMap<String, LogFile> { |
833 | 11 | let mut logs = HashMap::with_capacity(server_logs.len()); |
834 | 12 | for (k, v1 ) in server_logs { |
835 | 1 | logs.insert( |
836 | 1 | k.clone(), |
837 | 1 | LogFile { |
838 | 1 | digest: Some(v.into()), |
839 | 1 | human_readable: false, |
840 | 1 | }, |
841 | 1 | ); |
842 | 1 | } |
843 | 11 | logs |
844 | 11 | } |
845 | | |
846 | 11 | let status = Some( |
847 | 11 | action_result |
848 | 11 | .error |
849 | 11 | .clone() |
850 | 11 | .map_or_else(Status::default, Into::into), |
851 | 11 | ); |
852 | 11 | let message = action_result.message.clone(); |
853 | 11 | ExecuteResponse { |
854 | 11 | server_logs: logs_from(action_result.server_logs.clone()), |
855 | 11 | result: Some(action_result.into()), |
856 | 11 | cached_result: false, |
857 | 11 | status, |
858 | 11 | message, |
859 | 11 | } |
860 | 11 | } |
861 | | |
862 | | impl From<ActionStage> for ExecuteResponse { |
863 | 6 | fn from(val: ActionStage) -> Self { |
864 | 6 | match val { |
865 | | // We don't have an execute response if we don't have the results. It is defined |
866 | | // behavior to return an empty proto struct. |
867 | | ActionStage::Unknown |
868 | | | ActionStage::CacheCheck |
869 | | | ActionStage::Queued |
870 | 0 | | ActionStage::Executing => Self::default(), |
871 | 6 | ActionStage::Completed(action_result) => to_execute_response(action_result), |
872 | | // Handled separately as there are no server logs and the action |
873 | | // result is already in Proto format. |
874 | 0 | ActionStage::CompletedFromCache(proto_action_result) => Self { |
875 | 0 | server_logs: HashMap::new(), |
876 | 0 | result: Some(proto_action_result), |
877 | 0 | cached_result: true, |
878 | 0 | status: Some(Status::default()), |
879 | 0 | message: String::new(), // Will be populated later if applicable. |
880 | 0 | }, |
881 | | } |
882 | 6 | } |
883 | | } |
884 | | |
885 | | impl From<ActionResult> for ProtoActionResult { |
886 | 17 | fn from(val: ActionResult) -> Self { |
887 | 17 | let mut output_symlinks = Vec::with_capacity( |
888 | 17 | val.output_file_symlinks.len() + val.output_directory_symlinks.len(), |
889 | 17 | ); |
890 | 17 | output_symlinks.extend_from_slice(val.output_file_symlinks.as_slice()); |
891 | 17 | output_symlinks.extend_from_slice(val.output_directory_symlinks.as_slice()); |
892 | 17 | |
893 | 17 | Self { |
894 | 17 | output_files: val.output_files.into_iter().map(Into::into).collect(), |
895 | 17 | output_file_symlinks: val |
896 | 17 | .output_file_symlinks |
897 | 17 | .into_iter() |
898 | 17 | .map(Into::into) |
899 | 17 | .collect(), |
900 | 17 | output_symlinks: output_symlinks.into_iter().map(Into::into).collect(), |
901 | 17 | output_directories: val.output_folders.into_iter().map(Into::into).collect(), |
902 | 17 | output_directory_symlinks: val |
903 | 17 | .output_directory_symlinks |
904 | 17 | .into_iter() |
905 | 17 | .map(Into::into) |
906 | 17 | .collect(), |
907 | 17 | exit_code: val.exit_code, |
908 | 17 | stdout_raw: Bytes::default(), |
909 | 17 | stdout_digest: Some(val.stdout_digest.into()), |
910 | 17 | stderr_raw: Bytes::default(), |
911 | 17 | stderr_digest: Some(val.stderr_digest.into()), |
912 | 17 | execution_metadata: Some(val.execution_metadata.into()), |
913 | 17 | } |
914 | 17 | } |
915 | | } |
916 | | |
917 | | impl TryFrom<ProtoActionResult> for ActionResult { |
918 | | type Error = Error; |
919 | | |
920 | 0 | fn try_from(val: ProtoActionResult) -> Result<Self, Error> { |
921 | 0 | let output_file_symlinks = val |
922 | 0 | .output_file_symlinks |
923 | 0 | .into_iter() |
924 | 0 | .map(|output_symlink| { |
925 | 0 | SymlinkInfo::try_from(output_symlink) |
926 | 0 | .err_tip(|| "Output File Symlinks could not be converted to SymlinkInfo") |
927 | 0 | }) |
928 | 0 | .collect::<Result<Vec<_>, _>>()?; |
929 | | |
930 | 0 | let output_directory_symlinks = val |
931 | 0 | .output_directory_symlinks |
932 | 0 | .into_iter() |
933 | 0 | .map(|output_symlink| { |
934 | 0 | SymlinkInfo::try_from(output_symlink) |
935 | 0 | .err_tip(|| "Output File Symlinks could not be converted to SymlinkInfo") |
936 | 0 | }) |
937 | 0 | .collect::<Result<Vec<_>, _>>()?; |
938 | | |
939 | 0 | let output_files = val |
940 | 0 | .output_files |
941 | 0 | .into_iter() |
942 | 0 | .map(|output_file| { |
943 | 0 | output_file |
944 | 0 | .try_into() |
945 | 0 | .err_tip(|| "Output File could not be converted") |
946 | 0 | }) |
947 | 0 | .collect::<Result<Vec<_>, _>>()?; |
948 | | |
949 | 0 | let output_folders = val |
950 | 0 | .output_directories |
951 | 0 | .into_iter() |
952 | 0 | .map(|output_directory| { |
953 | 0 | output_directory |
954 | 0 | .try_into() |
955 | 0 | .err_tip(|| "Output File could not be converted") |
956 | 0 | }) |
957 | 0 | .collect::<Result<Vec<_>, _>>()?; |
958 | | |
959 | | Ok(Self { |
960 | 0 | output_files, |
961 | 0 | output_folders, |
962 | 0 | output_file_symlinks, |
963 | 0 | output_directory_symlinks, |
964 | 0 | exit_code: val.exit_code, |
965 | 0 | stdout_digest: val |
966 | 0 | .stdout_digest |
967 | 0 | .err_tip(|| "Expected stdout_digest to be set on ExecuteResponse msg")? |
968 | 0 | .try_into()?, |
969 | 0 | stderr_digest: val |
970 | 0 | .stderr_digest |
971 | 0 | .err_tip(|| "Expected stderr_digest to be set on ExecuteResponse msg")? |
972 | 0 | .try_into()?, |
973 | 0 | execution_metadata: val |
974 | 0 | .execution_metadata |
975 | 0 | .err_tip(|| "Expected execution_metadata to be set on ExecuteResponse msg")? |
976 | 0 | .try_into()?, |
977 | 0 | server_logs: Default::default(), |
978 | 0 | error: None, |
979 | 0 | message: String::new(), |
980 | | }) |
981 | 0 | } |
982 | | } |
983 | | |
984 | | impl TryFrom<ExecuteResponse> for ActionStage { |
985 | | type Error = Error; |
986 | | |
987 | 3 | fn try_from(execute_response: ExecuteResponse) -> Result<Self, Error> { |
988 | 3 | let proto_action_result = execute_response |
989 | 3 | .result |
990 | 3 | .err_tip(|| "Expected result to be set on ExecuteResponse msg"0 )?0 ; |
991 | 3 | let action_result = ActionResult { |
992 | 3 | output_files: proto_action_result |
993 | 3 | .output_files |
994 | 3 | .try_map(TryInto::try_into)?0 , |
995 | 3 | output_directory_symlinks: proto_action_result |
996 | 3 | .output_directory_symlinks |
997 | 3 | .try_map(TryInto::try_into)?0 , |
998 | 3 | output_file_symlinks: proto_action_result |
999 | 3 | .output_file_symlinks |
1000 | 3 | .try_map(TryInto::try_into)?0 , |
1001 | 3 | output_folders: proto_action_result |
1002 | 3 | .output_directories |
1003 | 3 | .try_map(TryInto::try_into)?0 , |
1004 | 3 | exit_code: proto_action_result.exit_code, |
1005 | 3 | |
1006 | 3 | stdout_digest: proto_action_result |
1007 | 3 | .stdout_digest |
1008 | 3 | .err_tip(|| "Expected stdout_digest to be set on ExecuteResponse msg"0 )?0 |
1009 | 3 | .try_into()?0 , |
1010 | 3 | stderr_digest: proto_action_result |
1011 | 3 | .stderr_digest |
1012 | 3 | .err_tip(|| "Expected stderr_digest to be set on ExecuteResponse msg"0 )?0 |
1013 | 3 | .try_into()?0 , |
1014 | 3 | execution_metadata: proto_action_result |
1015 | 3 | .execution_metadata |
1016 | 3 | .err_tip(|| "Expected execution_metadata to be set on ExecuteResponse msg"0 )?0 |
1017 | 3 | .try_into()?0 , |
1018 | 3 | server_logs: execute_response.server_logs.try_map(|v| { |
1019 | 2 | v.digest |
1020 | 2 | .err_tip(|| "Expected digest to be set on LogFile msg"0 )?0 |
1021 | 2 | .try_into() |
1022 | 3 | }2 )?0 , |
1023 | 3 | error: execute_response.status.clone().and_then(|v| { |
1024 | 3 | if v.code == 0 { Branch (1024:20): [True: 1, False: 2]
Branch (1024:20): [Folded - Ignored]
|
1025 | 1 | None |
1026 | | } else { |
1027 | 2 | Some(v.into()) |
1028 | | } |
1029 | 3 | }), |
1030 | 3 | message: execute_response.message, |
1031 | 3 | }; |
1032 | 3 | |
1033 | 3 | if execute_response.cached_result { Branch (1033:12): [True: 0, False: 3]
Branch (1033:12): [Folded - Ignored]
|
1034 | 0 | return Ok(Self::CompletedFromCache(action_result.into())); |
1035 | 3 | } |
1036 | 3 | Ok(Self::Completed(action_result)) |
1037 | 3 | } |
1038 | | } |
1039 | | |
1040 | | // TODO: Should be able to remove this after tokio-rs/prost#299 |
1041 | | trait TypeUrl: Message { |
1042 | | const TYPE_URL: &'static str; |
1043 | | } |
1044 | | |
1045 | | impl TypeUrl for ExecuteResponse { |
1046 | | const TYPE_URL: &'static str = |
1047 | | "type.googleapis.com/build.bazel.remote.execution.v2.ExecuteResponse"; |
1048 | | } |
1049 | | |
1050 | | impl TypeUrl for ExecuteOperationMetadata { |
1051 | | const TYPE_URL: &'static str = |
1052 | | "type.googleapis.com/build.bazel.remote.execution.v2.ExecuteOperationMetadata"; |
1053 | | } |
1054 | | |
1055 | 2 | fn from_any<T>(message: &Any) -> Result<T, Error> |
1056 | 2 | where |
1057 | 2 | T: TypeUrl + Default, |
1058 | 2 | { |
1059 | 0 | error_if!( |
1060 | 2 | message.type_url != T::TYPE_URL, Branch (1060:9): [True: 0, False: 1]
Branch (1060:9): [True: 0, False: 1]
Branch (1060:9): [Folded - Ignored]
|
1061 | | "Incorrect type when decoding Any. {} != {}", |
1062 | | message.type_url, |
1063 | 0 | T::TYPE_URL.to_string() |
1064 | | ); |
1065 | 2 | Ok(T::decode(message.value.as_slice())?0 ) |
1066 | 2 | } |
1067 | | |
1068 | 2 | fn to_any<T>(message: &T) -> Any |
1069 | 2 | where |
1070 | 2 | T: TypeUrl, |
1071 | 2 | { |
1072 | 2 | Any { |
1073 | 2 | type_url: T::TYPE_URL.to_string(), |
1074 | 2 | value: message.encode_to_vec(), |
1075 | 2 | } |
1076 | 2 | } |
1077 | | |
1078 | | /// Current state of the action. |
1079 | | /// This must be 100% compatible with `Operation` in `google/longrunning/operations.proto`. |
1080 | 8 | #[derive(PartialEq, Debug, Clone, Serialize, Deserialize, M0 etricsComponent0 )] |
1081 | | pub struct ActionState { |
1082 | | #[metric(help = "The current stage of the action.")] |
1083 | | pub stage: ActionStage, |
1084 | | #[metric(help = "The unique identifier of the action.")] |
1085 | | pub client_operation_id: OperationId, |
1086 | | #[metric(help = "The digest of the action.")] |
1087 | | pub action_digest: DigestInfo, |
1088 | | } |
1089 | | |
1090 | | impl ActionState { |
1091 | 1 | pub fn try_from_operation( |
1092 | 1 | operation: Operation, |
1093 | 1 | client_operation_id: OperationId, |
1094 | 1 | ) -> Result<Self, Error> { |
1095 | 1 | let metadata = from_any::<ExecuteOperationMetadata>( |
1096 | 1 | &operation |
1097 | 1 | .metadata |
1098 | 1 | .err_tip(|| "No metadata in upstream operation"0 )?0 , |
1099 | | ) |
1100 | 1 | .err_tip(|| "Could not decode metadata in upstream operation"0 )?0 ; |
1101 | | |
1102 | 1 | let stage = match execution_stage::Value::try_from(metadata.stage).err_tip(|| { |
1103 | 0 | format!( |
1104 | 0 | "Could not convert {} to execution_stage::Value", |
1105 | 0 | metadata.stage |
1106 | 0 | ) |
1107 | 1 | })?0 { |
1108 | 0 | execution_stage::Value::Unknown => ActionStage::Unknown, |
1109 | 0 | execution_stage::Value::CacheCheck => ActionStage::CacheCheck, |
1110 | 0 | execution_stage::Value::Queued => ActionStage::Queued, |
1111 | 0 | execution_stage::Value::Executing => ActionStage::Executing, |
1112 | | execution_stage::Value::Completed => { |
1113 | 1 | let execute_response = operation |
1114 | 1 | .result |
1115 | 1 | .err_tip(|| "No result data for completed upstream action"0 )?0 ; |
1116 | 1 | match execute_response { |
1117 | 0 | LongRunningResult::Error(error) => ActionStage::Completed(ActionResult { |
1118 | 0 | error: Some(error.into()), |
1119 | 0 | ..ActionResult::default() |
1120 | 0 | }), |
1121 | 1 | LongRunningResult::Response(response) => { |
1122 | 1 | // Could be Completed, CompletedFromCache or Error. |
1123 | 1 | from_any::<ExecuteResponse>(&response) |
1124 | 1 | .err_tip(|| { |
1125 | 0 | "Could not decode result structure for completed upstream action" |
1126 | 1 | })?0 |
1127 | 1 | .try_into()?0 |
1128 | | } |
1129 | | } |
1130 | | } |
1131 | | }; |
1132 | | |
1133 | 1 | let action_digest = metadata |
1134 | 1 | .action_digest |
1135 | 1 | .err_tip(|| "No action_digest in upstream operation"0 )?0 |
1136 | 1 | .try_into() |
1137 | 1 | .err_tip(|| "Could not convert action_digest into DigestInfo"0 )?0 ; |
1138 | | |
1139 | 1 | Ok(Self { |
1140 | 1 | stage, |
1141 | 1 | client_operation_id, |
1142 | 1 | action_digest, |
1143 | 1 | }) |
1144 | 1 | } |
1145 | | |
1146 | 1 | pub fn as_operation(&self, client_operation_id: OperationId) -> Operation { |
1147 | 1 | let stage = Into::<execution_stage::Value>::into(&self.stage) as i32; |
1148 | 1 | let name = client_operation_id.into_string(); |
1149 | | |
1150 | 1 | let result = if self.stage.has_action_result() { Branch (1150:25): [True: 1, False: 0]
Branch (1150:25): [Folded - Ignored]
|
1151 | 1 | let execute_response: ExecuteResponse = self.stage.clone().into(); |
1152 | 1 | Some(LongRunningResult::Response(to_any(&execute_response))) |
1153 | | } else { |
1154 | 0 | None |
1155 | | }; |
1156 | 1 | let digest = Some(self.action_digest.into()); |
1157 | 1 | |
1158 | 1 | let metadata = ExecuteOperationMetadata { |
1159 | 1 | stage, |
1160 | 1 | action_digest: digest, |
1161 | 1 | // TODO(blaise.bruer) We should support stderr/stdout streaming. |
1162 | 1 | stdout_stream_name: String::default(), |
1163 | 1 | stderr_stream_name: String::default(), |
1164 | 1 | partial_execution_metadata: None, |
1165 | 1 | }; |
1166 | 1 | |
1167 | 1 | Operation { |
1168 | 1 | name, |
1169 | 1 | metadata: Some(to_any(&metadata)), |
1170 | 1 | done: result.is_some(), |
1171 | 1 | result, |
1172 | 1 | } |
1173 | 1 | } |
1174 | | } |