Coverage Report

Created: 2026-12-01 07:53

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