Coverage Report

Created: 2026-07-21 15:28

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