Coverage Report

Created: 2026-07-21 15:28

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/build/source/nativelink-scheduler/src/grpc_scheduler.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::future::Future;
16
use core::time::Duration;
17
use std::collections::HashMap;
18
use std::sync::Arc;
19
20
use async_trait::async_trait;
21
use futures::stream::unfold;
22
use futures::{StreamExt, TryFutureExt};
23
use nativelink_config::schedulers::GrpcSpec;
24
use nativelink_error::{Code, Error, ResultExt, error_if, make_err};
25
use nativelink_metric::{MetricsComponent, RootMetricsComponent};
26
use nativelink_proto::build::bazel::remote::execution::v2::capabilities_client::CapabilitiesClient;
27
use nativelink_proto::build::bazel::remote::execution::v2::execution_client::ExecutionClient;
28
use nativelink_proto::build::bazel::remote::execution::v2::{
29
    ExecuteRequest, ExecutionPolicy, GetCapabilitiesRequest, WaitExecutionRequest,
30
};
31
use nativelink_proto::google::longrunning::Operation;
32
use nativelink_util::action_messages::{
33
    ActionInfo, ActionState, ActionUniqueQualifier, DEFAULT_EXECUTION_PRIORITY, OperationId,
34
};
35
use nativelink_util::connection_manager::ConnectionManager;
36
use nativelink_util::operation_state_manager::{
37
    ActionStateResult, ActionStateResultStream, ClientStateManager, OperationFilter,
38
};
39
use nativelink_util::origin_event::OriginMetadata;
40
use nativelink_util::retry::{Retrier, RetryResult};
41
use nativelink_util::{background_spawn, tls_utils};
42
use parking_lot::Mutex;
43
use tokio::select;
44
use tokio::sync::watch;
45
use tokio::time::sleep;
46
use tonic::{Request, Streaming};
47
use tracing::{error, info, warn};
48
49
use crate::known_platform_property_provider::KnownPlatformPropertyProvider;
50
51
struct GrpcActionStateResult {
52
    client_operation_id: OperationId,
53
    rx: watch::Receiver<Arc<ActionState>>,
54
}
55
56
#[async_trait]
57
impl ActionStateResult for GrpcActionStateResult {
58
0
    async fn as_state(&self) -> Result<(Arc<ActionState>, Option<OriginMetadata>), Error> {
59
        let mut action_state = self.rx.borrow().clone();
60
        Arc::make_mut(&mut action_state).client_operation_id = self.client_operation_id.clone();
61
        // TODO(palfrey) We currently don't support OriginMetadata in this implementation, but
62
        // we should.
63
        Ok((action_state, None))
64
0
    }
65
66
0
    async fn changed(&mut self) -> Result<(Arc<ActionState>, Option<OriginMetadata>), Error> {
67
0
        self.rx.changed().await.map_err(|e| {
68
0
            Error::from_std_err(Code::Internal, &e)
69
0
                .append("Channel closed in GrpcActionStateResult::changed")
70
0
        })?;
71
        let mut action_state = self.rx.borrow().clone();
72
        Arc::make_mut(&mut action_state).client_operation_id = self.client_operation_id.clone();
73
        // TODO(palfrey) We currently don't support OriginMetadata in this implementation, but
74
        // we should.
75
        Ok((action_state, None))
76
0
    }
77
78
0
    async fn as_action_info(&self) -> Result<(Arc<ActionInfo>, Option<OriginMetadata>), Error> {
79
        // TODO(palfrey) We should probably remove as_action_info()
80
        // or implement it properly.
81
        return Err(make_err!(
82
            Code::Unimplemented,
83
            "as_action_info not implemented for GrpcActionStateResult::as_action_info"
84
        ));
85
0
    }
86
}
87
88
#[derive(Debug, MetricsComponent)]
89
pub struct GrpcScheduler {
90
    #[metric(group = "property_managers")]
91
    supported_props: Mutex<HashMap<String, Vec<String>>>,
92
    retrier: Retrier,
93
    connection_manager: ConnectionManager,
94
}
95
96
impl GrpcScheduler {
97
0
    pub fn new(spec: &GrpcSpec) -> Result<Self, Error> {
98
0
        Self::new_with_jitter(spec, spec.retry.make_jitter_fn())
99
0
    }
100
101
0
    pub fn new_with_jitter(
102
0
        spec: &GrpcSpec,
103
0
        jitter_fn: Arc<dyn Fn(Duration) -> Duration + Send + Sync>,
104
0
    ) -> Result<Self, Error> {
105
0
        let endpoint = tls_utils::endpoint(&spec.endpoint)?;
106
        Ok(Self {
107
0
            supported_props: Mutex::new(HashMap::new()),
108
0
            retrier: Retrier::new(
109
0
                Arc::new(|duration| Box::pin(sleep(duration))),
110
0
                jitter_fn.clone(),
111
0
                spec.retry.clone(),
112
            ),
113
0
            connection_manager: ConnectionManager::new(
114
0
                core::iter::once(endpoint),
115
0
                spec.connections_per_endpoint,
116
0
                spec.max_concurrent_requests,
117
0
                spec.retry.clone(),
118
0
                jitter_fn,
119
            ),
120
        })
121
0
    }
122
123
0
    async fn perform_request<F, Fut, R, I>(&self, input: I, mut request: F) -> Result<R, Error>
124
0
    where
125
0
        F: FnMut(I) -> Fut + Send + Copy,
126
0
        Fut: Future<Output = Result<R, Error>> + Send,
127
0
        R: Send,
128
0
        I: Send + Clone,
129
0
    {
130
0
        self.retrier
131
0
            .retry(unfold(input, move |input| async move {
132
0
                let input_clone = input.clone();
133
                Some((
134
0
                    request(input_clone)
135
0
                        .await
136
0
                        .map_or_else(RetryResult::Retry, RetryResult::Ok),
137
0
                    input,
138
                ))
139
0
            }))
140
0
            .await
141
0
    }
142
143
0
    async fn stream_state(
144
0
        mut result_stream: Streaming<Operation>,
145
0
    ) -> Result<Box<dyn ActionStateResult>, Error> {
146
0
        if let Some(initial_response) = result_stream
147
0
            .message()
148
0
            .await
149
0
            .err_tip(|| "Receiving response from upstream scheduler")?
150
        {
151
0
            let client_operation_id = OperationId::from(initial_response.name.as_str());
152
            // Our operation_id is not needed here is just a place holder to recycle existing object.
153
            // The only thing that actually matters is the operation_id.
154
0
            let operation_id = OperationId::default();
155
0
            let action_state =
156
0
                ActionState::try_from_operation(initial_response, operation_id.clone())
157
0
                    .err_tip(|| "In GrpcScheduler::stream_state")?;
158
0
            let (tx, mut rx) = watch::channel(Arc::new(action_state));
159
0
            rx.mark_changed();
160
0
            background_spawn!("grpc_scheduler_stream_state", async move {
161
                loop {
162
0
                    select!(
163
0
                        () = tx.closed() => {
164
0
                            info!(
165
                                "Client disconnected in GrpcScheduler"
166
                            );
167
0
                            return;
168
                        }
169
0
                        response = result_stream.message() => {
170
                            // When the upstream closes the channel, close the
171
                            // downstream too.
172
0
                            let Ok(Some(response)) = response else {
173
0
                                return;
174
                            };
175
0
                            let maybe_action_state = ActionState::try_from_operation(response, operation_id.clone());
176
0
                            match maybe_action_state {
177
0
                                Ok(response) => {
178
0
                                    if let Err(err) = tx.send(Arc::new(response)) {
179
0
                                        info!(
180
                                            ?err,
181
                                            "Client error in GrpcScheduler"
182
                                        );
183
0
                                        return;
184
0
                                    }
185
                                }
186
0
                                Err(err) => {
187
0
                                    error!(
188
                                        ?err,
189
                                        "Error converting response to ActionState in GrpcScheduler"
190
                                    );
191
                                },
192
                            }
193
                        }
194
                    );
195
                }
196
0
            });
197
198
0
            return Ok(Box::new(GrpcActionStateResult {
199
0
                client_operation_id,
200
0
                rx,
201
0
            }));
202
0
        }
203
0
        Err(make_err!(
204
0
            Code::Internal,
205
0
            "Upstream scheduler didn't accept action."
206
0
        ))
207
0
    }
208
209
0
    async fn inner_get_known_properties(&self, instance_name: &str) -> Result<Vec<String>, Error> {
210
0
        if let Some(supported_props) = self.supported_props.lock().get(instance_name) {
211
0
            return Ok(supported_props.clone());
212
0
        }
213
214
0
        self.perform_request(instance_name, |instance_name| async move {
215
            // Not in the cache, lookup the capabilities with the upstream.
216
0
            let channel = self
217
0
                .connection_manager
218
0
                .connection("get_known_properties".into())
219
0
                .await
220
0
                .err_tip(|| "in get_platform_property_manager()")?;
221
0
            let capabilities_result = CapabilitiesClient::new(channel)
222
0
                .get_capabilities(GetCapabilitiesRequest {
223
0
                    instance_name: instance_name.to_string(),
224
0
                })
225
0
                .await
226
0
                .err_tip(|| "Retrieving upstream GrpcScheduler capabilities");
227
0
            let capabilities = capabilities_result?.into_inner();
228
0
            let supported_props = capabilities
229
0
                .execution_capabilities
230
0
                .err_tip(|| "Unable to get execution properties in GrpcScheduler")?
231
                .supported_node_properties
232
0
                .into_iter()
233
0
                .collect::<Vec<String>>();
234
235
0
            self.supported_props
236
0
                .lock()
237
0
                .insert(instance_name.to_string(), supported_props.clone());
238
0
            Ok(supported_props)
239
0
        })
240
0
        .await
241
0
    }
242
243
0
    async fn inner_add_action(
244
0
        &self,
245
0
        _client_operation_id: OperationId,
246
0
        action_info: Arc<ActionInfo>,
247
0
    ) -> Result<Box<dyn ActionStateResult>, Error> {
248
0
        let execution_policy = if action_info.priority == DEFAULT_EXECUTION_PRIORITY {
249
0
            None
250
        } else {
251
0
            Some(ExecutionPolicy {
252
0
                priority: action_info.priority,
253
0
            })
254
        };
255
0
        let skip_cache_lookup = match action_info.unique_qualifier {
256
0
            ActionUniqueQualifier::Cacheable(_) => false,
257
0
            ActionUniqueQualifier::Uncacheable(_) => true,
258
        };
259
0
        let request = ExecuteRequest {
260
0
            instance_name: action_info.instance_name().clone(),
261
0
            skip_cache_lookup,
262
0
            action_digest: Some(action_info.digest().into()),
263
0
            execution_policy,
264
0
            // TODO: Get me from the original request, not very important as we ignore it.
265
0
            results_cache_policy: None,
266
0
            digest_function: action_info
267
0
                .unique_qualifier
268
0
                .digest_function()
269
0
                .proto_digest_func()
270
0
                .into(),
271
0
        };
272
0
        let result_stream = self
273
0
            .perform_request(request, |request| async move {
274
0
                let channel = self
275
0
                    .connection_manager
276
0
                    .connection(format!("add_action: {:?}", request.action_digest))
277
0
                    .await
278
0
                    .err_tip(|| "in add_action()")?;
279
0
                ExecutionClient::new(channel)
280
0
                    .execute(Request::new(request))
281
0
                    .await
282
0
                    .err_tip(|| "Sending action to upstream scheduler")
283
0
            })
284
0
            .await?
285
0
            .into_inner();
286
0
        Self::stream_state(result_stream).await
287
0
    }
288
289
0
    async fn inner_filter_operations(
290
0
        &self,
291
0
        filter: OperationFilter,
292
0
    ) -> Result<ActionStateResultStream<'_>, Error> {
293
0
        error_if!(
294
0
            filter
295
0
                != OperationFilter {
296
0
                    client_operation_id: filter.client_operation_id.clone(),
297
0
                    ..Default::default()
298
0
                },
299
            "Unsupported filter in GrpcScheduler::filter_operations. Only client_operation_id is supported - {filter:?}"
300
        );
301
0
        let client_operation_id = filter.client_operation_id.ok_or_else(|| {
302
0
            make_err!(Code::InvalidArgument, "`client_operation_id` is the only supported filter in GrpcScheduler::filter_operations")
303
0
        })?;
304
0
        let request = WaitExecutionRequest {
305
0
            name: client_operation_id.to_string(),
306
0
        };
307
0
        let result_stream = self
308
0
            .perform_request(request, |request| async move {
309
0
                let channel = self
310
0
                    .connection_manager
311
0
                    .connection(format!("filter_operations: {}", request.name))
312
0
                    .await
313
0
                    .err_tip(|| "in find_by_client_operation_id()")?;
314
0
                ExecutionClient::new(channel)
315
0
                    .wait_execution(Request::new(request))
316
0
                    .await
317
0
                    .err_tip(|| "While getting wait_execution stream")
318
0
            })
319
0
            .and_then(|result_stream| Self::stream_state(result_stream.into_inner()))
320
0
            .await;
321
0
        match result_stream {
322
0
            Ok(result_stream) => Ok(unfold(
323
0
                Some(result_stream),
324
0
                |maybe_result_stream| async move { maybe_result_stream.map(|v| (v, None)) },
325
            )
326
0
            .boxed()),
327
0
            Err(err) => {
328
0
                warn!(?err, "Error looking up action with upstream scheduler");
329
0
                Ok(futures::stream::empty().boxed())
330
            }
331
        }
332
0
    }
333
}
334
335
#[async_trait]
336
impl ClientStateManager for GrpcScheduler {
337
    async fn add_action(
338
        &self,
339
        client_operation_id: OperationId,
340
        action_info: Arc<ActionInfo>,
341
0
    ) -> Result<Box<dyn ActionStateResult>, Error> {
342
        self.inner_add_action(client_operation_id, action_info)
343
            .await
344
0
    }
345
346
    async fn filter_operations<'a>(
347
        &'a self,
348
        filter: OperationFilter,
349
0
    ) -> Result<ActionStateResultStream<'a>, Error> {
350
        self.inner_filter_operations(filter).await
351
0
    }
352
}
353
354
#[async_trait]
355
impl KnownPlatformPropertyProvider for GrpcScheduler {
356
0
    async fn get_known_properties(&self, instance_name: &str) -> Result<Vec<String>, Error> {
357
        self.inner_get_known_properties(instance_name).await
358
0
    }
359
}
360
361
impl RootMetricsComponent for GrpcScheduler {}