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