Coverage Report

Created: 2025-05-08 18:47

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/build/source/nativelink-scheduler/src/memory_awaited_action_db.rs
Line
Count
Source
1
// Copyright 2024 The NativeLink Authors. All rights reserved.
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//    http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
15
use core::ops::{Bound, RangeBounds};
16
use std::collections::hash_map::Entry;
17
use std::collections::{BTreeMap, BTreeSet, HashMap};
18
use std::sync::Arc;
19
20
use async_lock::Mutex;
21
use futures::{FutureExt, Stream};
22
use nativelink_config::stores::EvictionPolicy;
23
use nativelink_error::{Code, Error, ResultExt, error_if, make_err};
24
use nativelink_metric::MetricsComponent;
25
use nativelink_util::action_messages::{
26
    ActionInfo, ActionStage, ActionUniqueKey, ActionUniqueQualifier, OperationId,
27
};
28
use nativelink_util::chunked_stream::ChunkedStream;
29
use nativelink_util::evicting_map::{EvictingMap, LenEntry};
30
use nativelink_util::instant_wrapper::InstantWrapper;
31
use nativelink_util::spawn;
32
use nativelink_util::task::JoinHandleDropGuard;
33
use tokio::sync::{Notify, mpsc, watch};
34
use tracing::{debug, error};
35
36
use crate::awaited_action_db::{
37
    AwaitedAction, AwaitedActionDb, AwaitedActionSubscriber, CLIENT_KEEPALIVE_DURATION,
38
    SortedAwaitedAction, SortedAwaitedActionState,
39
};
40
41
/// Number of events to process per cycle.
42
const MAX_ACTION_EVENTS_RX_PER_CYCLE: usize = 1024;
43
44
/// Represents a client that is currently listening to an action.
45
/// When the client is dropped, it will send the `AwaitedAction` to the
46
/// `event_tx` if there are other cleanups needed.
47
#[derive(Debug)]
48
struct ClientAwaitedAction {
49
    /// The `OperationId` that the client is listening to.
50
    operation_id: OperationId,
51
52
    /// The sender to notify of this struct being dropped.
53
    event_tx: mpsc::UnboundedSender<ActionEvent>,
54
}
55
56
impl ClientAwaitedAction {
57
27
    pub(crate) const fn new(
58
27
        operation_id: OperationId,
59
27
        event_tx: mpsc::UnboundedSender<ActionEvent>,
60
27
    ) -> Self {
61
27
        Self {
62
27
            operation_id,
63
27
            event_tx,
64
27
        }
65
27
    }
66
67
3
    pub(crate) const fn operation_id(&self) -> &OperationId {
68
3
        &self.operation_id
69
3
    }
70
}
71
72
impl Drop for ClientAwaitedAction {
73
27
    fn drop(&mut self) {
74
27
        // If we failed to send it means noone is listening.
75
27
        drop(self.event_tx.send(ActionEvent::ClientDroppedOperation(
76
27
            self.operation_id.clone(),
77
27
        )));
78
27
    }
79
}
80
81
/// Trait to be able to use the `EvictingMap` with `ClientAwaitedAction`.
82
/// Note: We only use `EvictingMap` for a time based eviction, which is
83
/// why the implementation has fixed default values in it.
84
impl LenEntry for ClientAwaitedAction {
85
    #[inline]
86
29
    fn len(&self) -> u64 {
87
29
        0
88
29
    }
89
90
    #[inline]
91
0
    fn is_empty(&self) -> bool {
92
0
        true
93
0
    }
94
}
95
96
/// Actions the `AwaitedActionsDb` needs to process.
97
#[derive(Debug)]
98
pub(crate) enum ActionEvent {
99
    /// A client has sent a keep alive message.
100
    ClientKeepAlive(OperationId),
101
    /// A client has dropped and pointed to `OperationId`.
102
    ClientDroppedOperation(OperationId),
103
}
104
105
/// Information required to track an individual client
106
/// keep alive config and state.
107
#[derive(Debug)]
108
struct ClientInfo<I: InstantWrapper, NowFn: Fn() -> I> {
109
    /// The client operation id.
110
    client_operation_id: OperationId,
111
    /// The last time a keep alive was sent.
112
    last_keep_alive: I,
113
    /// The function to get the current time.
114
    now_fn: NowFn,
115
    /// The sender to notify of this struct had an event.
116
    event_tx: mpsc::UnboundedSender<ActionEvent>,
117
}
118
119
/// Subscriber that clients can be used to monitor when `AwaitedActions` change.
120
#[derive(Debug)]
121
pub struct MemoryAwaitedActionSubscriber<I: InstantWrapper, NowFn: Fn() -> I> {
122
    /// The receiver to listen for changes.
123
    awaited_action_rx: watch::Receiver<AwaitedAction>,
124
    /// If a client id is known this is the info needed to keep the client
125
    /// action alive.
126
    client_info: Option<ClientInfo<I, NowFn>>,
127
}
128
129
impl<I: InstantWrapper, NowFn: Fn() -> I> MemoryAwaitedActionSubscriber<I, NowFn> {
130
583
    fn new(mut awaited_action_rx: watch::Receiver<AwaitedAction>) -> Self {
131
583
        awaited_action_rx.mark_changed();
132
583
        Self {
133
583
            awaited_action_rx,
134
583
            client_info: None,
135
583
        }
136
583
    }
137
138
30
    fn new_with_client(
139
30
        mut awaited_action_rx: watch::Receiver<AwaitedAction>,
140
30
        client_operation_id: OperationId,
141
30
        event_tx: mpsc::UnboundedSender<ActionEvent>,
142
30
        now_fn: NowFn,
143
30
    ) -> Self
144
30
    where
145
30
        NowFn: Fn() -> I,
146
30
    {
147
30
        awaited_action_rx.mark_changed();
148
30
        Self {
149
30
            awaited_action_rx,
150
30
            client_info: Some(ClientInfo {
151
30
                client_operation_id,
152
30
                last_keep_alive: I::from_secs(0),
153
30
                now_fn,
154
30
                event_tx,
155
30
            }),
156
30
        }
157
30
    }
158
}
159
160
impl<I, NowFn> AwaitedActionSubscriber for MemoryAwaitedActionSubscriber<I, NowFn>
161
where
162
    I: InstantWrapper,
163
    NowFn: Fn() -> I + Send + Sync + 'static,
164
{
165
58
    async fn changed(&mut self) -> Result<AwaitedAction, Error> {
166
44
        let client_operation_id = {
167
58
            let changed_fut = self.awaited_action_rx.changed().map(|r| {
168
44
                r.map_err(|e| {
169
0
                    make_err!(
170
0
                        Code::Internal,
171
0
                        "Failed to wait for awaited action to change {e:?}"
172
0
                    )
173
0
                })
174
44
            });
175
58
            let Some(client_info) = self.client_info.as_mut() else {
  Branch (175:17): [True: 0, False: 0]
  Branch (175:17): [Folded - Ignored]
  Branch (175:17): [True: 58, False: 0]
176
0
                changed_fut.await?;
177
0
                return Ok(self.awaited_action_rx.borrow().clone());
178
            };
179
58
            tokio::pin!(changed_fut);
180
            loop {
181
162
                if client_info.last_keep_alive.elapsed() > CLIENT_KEEPALIVE_DURATION {
  Branch (181:20): [True: 0, False: 0]
  Branch (181:20): [Folded - Ignored]
  Branch (181:20): [True: 55, False: 107]
182
55
                    client_info.last_keep_alive = (client_info.now_fn)();
183
55
                    // Failing to send just means our receiver dropped.
184
55
                    drop(client_info.event_tx.send(ActionEvent::ClientKeepAlive(
185
55
                        client_info.client_operation_id.clone(),
186
55
                    )));
187
107
                }
188
162
                let sleep_fut = (client_info.now_fn)().sleep(CLIENT_KEEPALIVE_DURATION);
189
162
                tokio::select! {
190
162
                    
result44
= &mut changed_fut => {
191
44
                        result
?0
;
192
44
                        break;
193
                    }
194
162
                    () = sleep_fut => {
195
104
                        // If we haven't received any updates for a while, we should
196
104
                        // let the database know that we are still listening to prevent
197
104
                        // the action from being dropped.
198
104
                    }
199
                }
200
            }
201
44
            client_info.client_operation_id.clone()
202
44
        };
203
44
        // At this stage we know that this event is a client request, so we need
204
44
        // to populate the client_operation_id.
205
44
        let mut awaited_action = self.awaited_action_rx.borrow().clone();
206
44
        awaited_action.set_client_operation_id(client_operation_id);
207
44
        Ok(awaited_action)
208
44
    }
209
210
668
    async fn borrow(&self) -> Result<AwaitedAction, Error> {
211
668
        let mut awaited_action = self.awaited_action_rx.borrow().clone();
212
668
        if let Some(
client_info16
) = self.client_info.as_ref() {
  Branch (212:16): [True: 0, False: 0]
  Branch (212:16): [Folded - Ignored]
  Branch (212:16): [True: 16, False: 652]
213
16
            awaited_action.set_client_operation_id(client_info.client_operation_id.clone());
214
652
        }
215
668
        Ok(awaited_action)
216
668
    }
217
}
218
219
/// A struct that is used to keep the devloper from trying to
220
/// return early from a function.
221
struct NoEarlyReturn;
222
223
#[derive(Debug, Default, MetricsComponent)]
224
struct SortedAwaitedActions {
225
    #[metric(group = "unknown")]
226
    unknown: BTreeSet<SortedAwaitedAction>,
227
    #[metric(group = "cache_check")]
228
    cache_check: BTreeSet<SortedAwaitedAction>,
229
    #[metric(group = "queued")]
230
    queued: BTreeSet<SortedAwaitedAction>,
231
    #[metric(group = "executing")]
232
    executing: BTreeSet<SortedAwaitedAction>,
233
    #[metric(group = "completed")]
234
    completed: BTreeSet<SortedAwaitedAction>,
235
}
236
237
impl SortedAwaitedActions {
238
39
    const fn btree_for_state(&mut self, state: &ActionStage) -> &mut BTreeSet<SortedAwaitedAction> {
239
39
        match state {
240
0
            ActionStage::Unknown => &mut self.unknown,
241
0
            ActionStage::CacheCheck => &mut self.cache_check,
242
26
            ActionStage::Queued => &mut self.queued,
243
13
            ActionStage::Executing => &mut self.executing,
244
0
            ActionStage::Completed(_) | ActionStage::CompletedFromCache(_) => &mut self.completed,
245
        }
246
39
    }
247
248
63
    fn insert_sort_map_for_stage(
249
63
        &mut self,
250
63
        stage: &ActionStage,
251
63
        sorted_awaited_action: &SortedAwaitedAction,
252
63
    ) -> Result<(), Error> {
253
63
        let newly_inserted = match stage {
254
0
            ActionStage::Unknown => self.unknown.insert(sorted_awaited_action.clone()),
255
0
            ActionStage::CacheCheck => self.cache_check.insert(sorted_awaited_action.clone()),
256
31
            ActionStage::Queued => self.queued.insert(sorted_awaited_action.clone()),
257
26
            ActionStage::Executing => self.executing.insert(sorted_awaited_action.clone()),
258
6
            ActionStage::Completed(_) => self.completed.insert(sorted_awaited_action.clone()),
259
            ActionStage::CompletedFromCache(_) => {
260
0
                self.completed.insert(sorted_awaited_action.clone())
261
            }
262
        };
263
63
        if !newly_inserted {
  Branch (263:12): [True: 0, False: 63]
  Branch (263:12): [Folded - Ignored]
264
0
            return Err(make_err!(
265
0
                Code::Internal,
266
0
                "Tried to insert an action that was already in the sorted map. This should never happen. {:?} - {:?}",
267
0
                stage,
268
0
                sorted_awaited_action
269
0
            ));
270
63
        }
271
63
        Ok(())
272
63
    }
273
274
39
    fn process_state_changes(
275
39
        &mut self,
276
39
        old_awaited_action: &AwaitedAction,
277
39
        new_awaited_action: &AwaitedAction,
278
39
    ) -> Result<(), Error> {
279
39
        let btree = self.btree_for_state(&old_awaited_action.state().stage);
280
39
        let maybe_sorted_awaited_action = btree.take(&SortedAwaitedAction {
281
39
            sort_key: old_awaited_action.sort_key(),
282
39
            operation_id: new_awaited_action.operation_id().clone(),
283
39
        });
284
285
39
        let Some(sorted_awaited_action) = maybe_sorted_awaited_action else {
  Branch (285:13): [True: 39, False: 0]
  Branch (285:13): [Folded - Ignored]
286
0
            return Err(make_err!(
287
0
                Code::Internal,
288
0
                "sorted_action_info_hash_keys and action_info_hash_key_to_awaited_action are out of sync - {} - {:?}",
289
0
                new_awaited_action.operation_id(),
290
0
                new_awaited_action,
291
0
            ));
292
        };
293
294
39
        self.insert_sort_map_for_stage(&new_awaited_action.state().stage, &sorted_awaited_action)
295
39
            .err_tip(|| 
"In AwaitedActionDb::update_awaited_action"0
)
?0
;
296
39
        Ok(())
297
39
    }
298
}
299
300
/// The database for storing the state of all actions.
301
#[derive(Debug, MetricsComponent)]
302
pub struct AwaitedActionDbImpl<I: InstantWrapper, NowFn: Fn() -> I> {
303
    /// A lookup table to lookup the state of an action by its client operation id.
304
    #[metric(group = "client_operation_ids")]
305
    client_operation_to_awaited_action: EvictingMap<OperationId, Arc<ClientAwaitedAction>, I>,
306
307
    /// A lookup table to lookup the state of an action by its worker operation id.
308
    #[metric(group = "operation_ids")]
309
    operation_id_to_awaited_action: BTreeMap<OperationId, watch::Sender<AwaitedAction>>,
310
311
    /// A lookup table to lookup the state of an action by its unique qualifier.
312
    #[metric(group = "action_info_hash_key_to_awaited_action")]
313
    action_info_hash_key_to_awaited_action: HashMap<ActionUniqueKey, OperationId>,
314
315
    /// A sorted set of [`AwaitedAction`]s. A wrapper is used to perform sorting
316
    /// based on the [`AwaitedActionSortKey`] of the [`AwaitedAction`].
317
    ///
318
    /// See [`AwaitedActionSortKey`] for more information on the ordering.
319
    #[metric(group = "sorted_action_infos")]
320
    sorted_action_info_hash_keys: SortedAwaitedActions,
321
322
    /// The number of connected clients for each operation id.
323
    #[metric(group = "connected_clients_for_operation_id")]
324
    connected_clients_for_operation_id: HashMap<OperationId, usize>,
325
326
    /// Where to send notifications about important events related to actions.
327
    action_event_tx: mpsc::UnboundedSender<ActionEvent>,
328
329
    /// The function to get the current time.
330
    now_fn: NowFn,
331
}
332
333
impl<I: InstantWrapper, NowFn: Fn() -> I + Clone + Send + Sync> AwaitedActionDbImpl<I, NowFn> {
334
3
    async fn get_awaited_action_by_id(
335
3
        &self,
336
3
        client_operation_id: &OperationId,
337
3
    ) -> Result<Option<MemoryAwaitedActionSubscriber<I, NowFn>>, Error> {
338
3
        let maybe_client_awaited_action = self
339
3
            .client_operation_to_awaited_action
340
3
            .get(client_operation_id)
341
3
            .await;
342
3
        let Some(client_awaited_action) = maybe_client_awaited_action else {
  Branch (342:13): [True: 0, False: 0]
  Branch (342:13): [Folded - Ignored]
  Branch (342:13): [True: 3, False: 0]
343
0
            return Ok(None);
344
        };
345
346
3
        self.operation_id_to_awaited_action
347
3
            .get(client_awaited_action.operation_id())
348
3
            .map(|tx| {
349
3
                Some(MemoryAwaitedActionSubscriber::new_with_client(
350
3
                    tx.subscribe(),
351
3
                    client_operation_id.clone(),
352
3
                    self.action_event_tx.clone(),
353
3
                    self.now_fn.clone(),
354
3
                ))
355
3
            })
356
3
            .ok_or_else(|| {
357
0
                make_err!(
358
0
                    Code::Internal,
359
0
                    "Failed to get client operation id {client_operation_id:?}"
360
0
                )
361
0
            })
362
3
    }
363
364
    /// Processes action events that need to be handled by the database.
365
55
    async fn handle_action_events(
366
55
        &mut self,
367
55
        action_events: impl IntoIterator<Item = ActionEvent>,
368
55
    ) -> NoEarlyReturn {
369
110
        for 
action55
in action_events {
370
55
            debug!(?action, 
"Handling action"0
);
371
55
            match action {
372
1
                ActionEvent::ClientDroppedOperation(operation_id) => {
373
                    // Cleanup operation_id_to_awaited_action.
374
1
                    let Some(tx) = self.operation_id_to_awaited_action.remove(&operation_id) else {
  Branch (374:25): [True: 0, False: 0]
  Branch (374:25): [Folded - Ignored]
  Branch (374:25): [True: 1, False: 0]
375
0
                        error!(
376
                            ?operation_id,
377
0
                            "operation_id_to_awaited_action does not have operation_id"
378
                        );
379
0
                        continue;
380
                    };
381
382
1
                    let connected_clients = match self
383
1
                        .connected_clients_for_operation_id
384
1
                        .entry(operation_id.clone())
385
                    {
386
1
                        Entry::Occupied(entry) => {
387
1
                            let value = *entry.get();
388
1
                            entry.remove();
389
1
                            value - 1
390
                        }
391
                        Entry::Vacant(_) => {
392
0
                            error!(
393
                                ?operation_id,
394
0
                                "connected_clients_for_operation_id does not have operation_id"
395
                            );
396
0
                            0
397
                        }
398
                    };
399
400
                    // Note: It is rare to have more than one client listening
401
                    // to the same action, so we assume that we are the last
402
                    // client and insert it back into the map if we detect that
403
                    // there are still clients listening (ie: the happy path
404
                    // is operation.connected_clients == 0).
405
1
                    if connected_clients != 0 {
  Branch (405:24): [True: 0, False: 0]
  Branch (405:24): [Folded - Ignored]
  Branch (405:24): [True: 1, False: 0]
406
1
                        self.operation_id_to_awaited_action
407
1
                            .insert(operation_id.clone(), tx);
408
1
                        self.connected_clients_for_operation_id
409
1
                            .insert(operation_id, connected_clients);
410
1
                        continue;
411
0
                    }
412
0
                    debug!(?operation_id, "Clearing operation from state manager");
413
0
                    let awaited_action = tx.borrow().clone();
414
0
                    // Cleanup action_info_hash_key_to_awaited_action if it was marked cached.
415
0
                    match &awaited_action.action_info().unique_qualifier {
416
0
                        ActionUniqueQualifier::Cachable(action_key) => {
417
0
                            let maybe_awaited_action = self
418
0
                                .action_info_hash_key_to_awaited_action
419
0
                                .remove(action_key);
420
0
                            if !awaited_action.state().stage.is_finished()
  Branch (420:32): [True: 0, False: 0]
  Branch (420:32): [Folded - Ignored]
  Branch (420:32): [True: 0, False: 0]
421
0
                                && maybe_awaited_action.is_none()
  Branch (421:36): [True: 0, False: 0]
  Branch (421:36): [Folded - Ignored]
  Branch (421:36): [True: 0, False: 0]
422
                            {
423
0
                                error!(
424
                                    ?operation_id,
425
                                    ?awaited_action,
426
                                    ?action_key,
427
0
                                    "action_info_hash_key_to_awaited_action and operation_id_to_awaited_action are out of sync",
428
                                );
429
0
                            }
430
                        }
431
0
                        ActionUniqueQualifier::Uncachable(_action_key) => {
432
0
                            // This Operation should not be in the hash_key map.
433
0
                        }
434
                    }
435
436
                    // Cleanup sorted_awaited_action.
437
0
                    let sort_key = awaited_action.sort_key();
438
0
                    let sort_btree_for_state = self
439
0
                        .sorted_action_info_hash_keys
440
0
                        .btree_for_state(&awaited_action.state().stage);
441
0
442
0
                    let maybe_sorted_awaited_action =
443
0
                        sort_btree_for_state.take(&SortedAwaitedAction {
444
0
                            sort_key,
445
0
                            operation_id: operation_id.clone(),
446
0
                        });
447
0
                    if maybe_sorted_awaited_action.is_none() {
  Branch (447:24): [True: 0, False: 0]
  Branch (447:24): [Folded - Ignored]
  Branch (447:24): [True: 0, False: 0]
448
0
                        error!(
449
                            ?operation_id,
450
                            ?sort_key,
451
0
                            "Expected maybe_sorted_awaited_action to have {sort_key:?}",
452
                        );
453
0
                    }
454
                }
455
54
                ActionEvent::ClientKeepAlive(client_id) => {
456
54
                    if let Some(client_awaited_action) = self
  Branch (456:28): [True: 0, False: 0]
  Branch (456:28): [Folded - Ignored]
  Branch (456:28): [True: 54, False: 0]
457
54
                        .client_operation_to_awaited_action
458
54
                        .get(&client_id)
459
54
                        .await
460
                    {
461
54
                        if let Some(awaited_action_sender) = self
  Branch (461:32): [True: 0, False: 0]
  Branch (461:32): [Folded - Ignored]
  Branch (461:32): [True: 54, False: 0]
462
54
                            .operation_id_to_awaited_action
463
54
                            .get(&client_awaited_action.operation_id)
464
                        {
465
54
                            awaited_action_sender.send_if_modified(|awaited_action| {
466
54
                                awaited_action.update_client_keep_alive((self.now_fn)().now());
467
54
                                false
468
54
                            });
469
0
                        }
470
                    } else {
471
0
                        error!(
472
                            ?client_id,
473
0
                            "client_operation_to_awaited_action does not have client_id",
474
                        );
475
                    }
476
                }
477
            }
478
        }
479
55
        NoEarlyReturn
480
55
    }
481
482
0
    fn get_awaited_actions_range(
483
0
        &self,
484
0
        start: Bound<&OperationId>,
485
0
        end: Bound<&OperationId>,
486
0
    ) -> impl Iterator<Item = (&'_ OperationId, MemoryAwaitedActionSubscriber<I, NowFn>)>
487
0
    + use<'_, I, NowFn> {
488
0
        self.operation_id_to_awaited_action
489
0
            .range((start, end))
490
0
            .map(|(operation_id, tx)| {
491
0
                (
492
0
                    operation_id,
493
0
                    MemoryAwaitedActionSubscriber::<I, NowFn>::new(tx.subscribe()),
494
0
                )
495
0
            })
496
0
    }
497
498
583
    fn get_by_operation_id(
499
583
        &self,
500
583
        operation_id: &OperationId,
501
583
    ) -> Option<MemoryAwaitedActionSubscriber<I, NowFn>> {
502
583
        self.operation_id_to_awaited_action
503
583
            .get(operation_id)
504
583
            .map(|tx| MemoryAwaitedActionSubscriber::<I, NowFn>::new(tx.subscribe()))
505
583
    }
506
507
1.13k
    fn get_range_of_actions(
508
1.13k
        &self,
509
1.13k
        state: SortedAwaitedActionState,
510
1.13k
        range: impl RangeBounds<SortedAwaitedAction>,
511
1.13k
    ) -> impl DoubleEndedIterator<
512
1.13k
        Item = Result<
513
1.13k
            (
514
1.13k
                &SortedAwaitedAction,
515
1.13k
                MemoryAwaitedActionSubscriber<I, NowFn>,
516
1.13k
            ),
517
1.13k
            Error,
518
1.13k
        >,
519
1.13k
    > {
520
1.13k
        let btree = match state {
521
0
            SortedAwaitedActionState::CacheCheck => &self.sorted_action_info_hash_keys.cache_check,
522
1.13k
            SortedAwaitedActionState::Queued => &self.sorted_action_info_hash_keys.queued,
523
0
            SortedAwaitedActionState::Executing => &self.sorted_action_info_hash_keys.executing,
524
0
            SortedAwaitedActionState::Completed => &self.sorted_action_info_hash_keys.completed,
525
        };
526
1.13k
        btree.range(range).map(|sorted_awaited_action| {
527
543
            let operation_id = &sorted_awaited_action.operation_id;
528
543
            self.get_by_operation_id(operation_id)
529
543
                .ok_or_else(|| {
530
0
                    make_err!(
531
0
                        Code::Internal,
532
0
                        "Failed to get operation id {}",
533
0
                        operation_id
534
0
                    )
535
0
                })
536
543
                .map(|subscriber| (sorted_awaited_action, subscriber))
537
543
        })
538
1.13k
    }
539
540
39
    fn process_state_changes_for_hash_key_map(
541
39
        action_info_hash_key_to_awaited_action: &mut HashMap<ActionUniqueKey, OperationId>,
542
39
        new_awaited_action: &AwaitedAction,
543
39
    ) {
544
39
        // Only process changes if the stage is not finished.
545
39
        if !new_awaited_action.state().stage.is_finished() {
  Branch (545:12): [True: 0, False: 0]
  Branch (545:12): [Folded - Ignored]
  Branch (545:12): [True: 33, False: 6]
546
33
            return;
547
6
        }
548
6
        match &new_awaited_action.action_info().unique_qualifier {
549
6
            ActionUniqueQualifier::Cachable(action_key) => {
550
6
                let maybe_awaited_action =
551
6
                    action_info_hash_key_to_awaited_action.remove(action_key);
552
6
                match maybe_awaited_action {
553
6
                    Some(removed_operation_id) => {
554
6
                        if &removed_operation_id != new_awaited_action.operation_id() {
  Branch (554:28): [True: 0, False: 0]
  Branch (554:28): [Folded - Ignored]
  Branch (554:28): [True: 0, False: 6]
555
0
                            error!(
556
                                ?removed_operation_id,
557
                                ?new_awaited_action,
558
                                ?action_key,
559
0
                                "action_info_hash_key_to_awaited_action and operation_id_to_awaited_action are out of sync",
560
                            );
561
6
                        }
562
                    }
563
                    None => {
564
0
                        error!(
565
                            ?new_awaited_action,
566
                            ?action_key,
567
0
                            "action_info_hash_key_to_awaited_action out of sync, it should have had the unique_key",
568
                        );
569
                    }
570
                }
571
            }
572
0
            ActionUniqueQualifier::Uncachable(_action_key) => {
573
0
                // If we are not cachable, the action should not be in the
574
0
                // hash_key map, so we don't need to process anything in
575
0
                // action_info_hash_key_to_awaited_action.
576
0
            }
577
        }
578
39
    }
579
580
39
    fn update_awaited_action(
581
39
        &mut self,
582
39
        mut new_awaited_action: AwaitedAction,
583
39
    ) -> Result<(), Error> {
584
39
        let tx = self
585
39
            .operation_id_to_awaited_action
586
39
            .get(new_awaited_action.operation_id())
587
39
            .ok_or_else(|| {
588
0
                make_err!(
589
0
                    Code::Internal,
590
0
                    "OperationId does not exist in map in AwaitedActionDb::update_awaited_action"
591
0
                )
592
0
            })?;
593
        {
594
            // Note: It's important to drop old_awaited_action before we call
595
            // send_replace or we will have a deadlock.
596
39
            let old_awaited_action = tx.borrow();
597
39
598
39
            // Do not process changes if the action version is not in sync with
599
39
            // what the sender based the update on.
600
39
            if old_awaited_action.version() != new_awaited_action.version() {
  Branch (600:16): [True: 0, False: 0]
  Branch (600:16): [Folded - Ignored]
  Branch (600:16): [True: 0, False: 39]
601
0
                return Err(make_err!(
602
0
                    // From: https://grpc.github.io/grpc/core/md_doc_statuscodes.html
603
0
                    // Use ABORTED if the client should retry at a higher level
604
0
                    // (e.g., when a client-specified test-and-set fails,
605
0
                    // indicating the client should restart a read-modify-write
606
0
                    // sequence)
607
0
                    Code::Aborted,
608
0
                    "{} Expected {} but got {} for operation_id {:?} - {:?}",
609
0
                    "Tried to update an awaited action with an incorrect version.",
610
0
                    old_awaited_action.version(),
611
0
                    new_awaited_action.version(),
612
0
                    old_awaited_action,
613
0
                    new_awaited_action,
614
0
                ));
615
39
            }
616
39
            new_awaited_action.increment_version();
617
618
0
            error_if!(
619
39
                old_awaited_action.action_info().unique_qualifier
  Branch (619:17): [True: 0, False: 0]
  Branch (619:17): [Folded - Ignored]
  Branch (619:17): [True: 0, False: 39]
620
39
                    != new_awaited_action.action_info().unique_qualifier,
621
                "Unique key changed for operation_id {:?} - {:?} - {:?}",
622
0
                new_awaited_action.operation_id(),
623
0
                old_awaited_action.action_info(),
624
0
                new_awaited_action.action_info(),
625
            );
626
39
            let is_same_stage = old_awaited_action
627
39
                .state()
628
39
                .stage
629
39
                .is_same_stage(&new_awaited_action.state().stage);
630
39
631
39
            if !is_same_stage {
  Branch (631:16): [True: 0, False: 0]
  Branch (631:16): [Folded - Ignored]
  Branch (631:16): [True: 39, False: 0]
632
39
                self.sorted_action_info_hash_keys
633
39
                    .process_state_changes(&old_awaited_action, &new_awaited_action)
?0
;
634
39
                Self::process_state_changes_for_hash_key_map(
635
39
                    &mut self.action_info_hash_key_to_awaited_action,
636
39
                    &new_awaited_action,
637
                );
638
0
            }
639
        }
640
641
        // Notify all listeners of the new state and ignore if no one is listening.
642
        // Note: Do not use `.send()` as it will not update the state if all listeners
643
        // are dropped.
644
39
        drop(tx.send_replace(new_awaited_action));
645
39
646
39
        Ok(())
647
39
    }
648
649
    /// Creates a new [`ClientAwaitedAction`] and a [`watch::Receiver`] to
650
    /// listen for changes. We don't do this in-line because it is important
651
    /// to ALWAYS construct a [`ClientAwaitedAction`] before inserting it into
652
    /// the map. Failing to do so may result in memory leaks. This is because
653
    /// [`ClientAwaitedAction`] implements a drop function that will trigger
654
    /// cleanup of the other maps on drop.
655
24
    fn make_client_awaited_action(
656
24
        &mut self,
657
24
        operation_id: &OperationId,
658
24
        awaited_action: AwaitedAction,
659
24
    ) -> (Arc<ClientAwaitedAction>, watch::Receiver<AwaitedAction>) {
660
24
        let (tx, rx) = watch::channel(awaited_action);
661
24
        let client_awaited_action = Arc::new(ClientAwaitedAction::new(
662
24
            operation_id.clone(),
663
24
            self.action_event_tx.clone(),
664
24
        ));
665
24
        self.operation_id_to_awaited_action
666
24
            .insert(operation_id.clone(), tx);
667
24
        self.connected_clients_for_operation_id
668
24
            .insert(operation_id.clone(), 1);
669
24
        (client_awaited_action, rx)
670
24
    }
671
672
27
    async fn add_action(
673
27
        &mut self,
674
27
        client_operation_id: OperationId,
675
27
        action_info: Arc<ActionInfo>,
676
27
    ) -> Result<MemoryAwaitedActionSubscriber<I, NowFn>, Error> {
677
        // Check to see if the action is already known and subscribe if it is.
678
27
        let subscription_result = self
679
27
            .try_subscribe(
680
27
                &client_operation_id,
681
27
                &action_info.unique_qualifier,
682
27
                action_info.priority,
683
27
            )
684
27
            .await
685
27
            .err_tip(|| 
"In AwaitedActionDb::subscribe_or_add_action"0
);
686
27
        match subscription_result {
687
0
            Err(err) => return Err(err),
688
3
            Ok(Some(subscription)) => return Ok(subscription),
689
24
            Ok(None) => { /* Add item to queue. */ }
690
        }
691
692
24
        let maybe_unique_key = match &action_info.unique_qualifier {
693
24
            ActionUniqueQualifier::Cachable(unique_key) => Some(unique_key.clone()),
694
0
            ActionUniqueQualifier::Uncachable(_unique_key) => None,
695
        };
696
24
        let operation_id = OperationId::default();
697
24
        let awaited_action =
698
24
            AwaitedAction::new(operation_id.clone(), action_info, (self.now_fn)().now());
699
24
        debug_assert!(
700
0
            ActionStage::Queued == awaited_action.state().stage,
701
0
            "Expected action to be queued"
702
        );
703
24
        let sort_key = awaited_action.sort_key();
704
24
705
24
        let (client_awaited_action, rx) =
706
24
            self.make_client_awaited_action(&operation_id.clone(), awaited_action);
707
24
708
24
        debug!(
709
            ?client_operation_id,
710
            ?operation_id,
711
            ?client_awaited_action,
712
0
            "Adding action"
713
        );
714
715
24
        self.client_operation_to_awaited_action
716
24
            .insert(client_operation_id.clone(), client_awaited_action)
717
24
            .await;
718
719
        // Note: We only put items in the map that are cachable.
720
24
        if let Some(unique_key) = maybe_unique_key {
  Branch (720:16): [True: 0, False: 0]
  Branch (720:16): [Folded - Ignored]
  Branch (720:16): [True: 24, False: 0]
721
24
            let old_value = self
722
24
                .action_info_hash_key_to_awaited_action
723
24
                .insert(unique_key, operation_id.clone());
724
24
            if let Some(
old_value0
) = old_value {
  Branch (724:20): [True: 0, False: 0]
  Branch (724:20): [Folded - Ignored]
  Branch (724:20): [True: 0, False: 24]
725
0
                error!(
726
                    ?operation_id,
727
                    ?old_value,
728
0
                    "action_info_hash_key_to_awaited_action already has unique_key"
729
                );
730
24
            }
731
0
        }
732
733
24
        self.sorted_action_info_hash_keys
734
24
            .insert_sort_map_for_stage(
735
24
                &ActionStage::Queued,
736
24
                &SortedAwaitedAction {
737
24
                    sort_key,
738
24
                    operation_id,
739
24
                },
740
24
            )
741
24
            .err_tip(|| 
"In AwaitedActionDb::subscribe_or_add_action"0
)
?0
;
742
743
24
        Ok(MemoryAwaitedActionSubscriber::new_with_client(
744
24
            rx,
745
24
            client_operation_id,
746
24
            self.action_event_tx.clone(),
747
24
            self.now_fn.clone(),
748
24
        ))
749
27
    }
750
751
27
    async fn try_subscribe(
752
27
        &mut self,
753
27
        client_operation_id: &OperationId,
754
27
        unique_qualifier: &ActionUniqueQualifier,
755
27
        // TODO(aaronmondal) To simplify the scheduler 2024 refactor, we
756
27
        // removed the ability to upgrade priorities of actions.
757
27
        // we should add priority upgrades back in.
758
27
        _priority: i32,
759
27
    ) -> Result<Option<MemoryAwaitedActionSubscriber<I, NowFn>>, Error> {
760
27
        let unique_key = match unique_qualifier {
761
27
            ActionUniqueQualifier::Cachable(unique_key) => unique_key,
762
0
            ActionUniqueQualifier::Uncachable(_unique_key) => return Ok(None),
763
        };
764
765
27
        let Some(
operation_id3
) = self.action_info_hash_key_to_awaited_action.get(unique_key) else {
  Branch (765:13): [True: 0, False: 0]
  Branch (765:13): [Folded - Ignored]
  Branch (765:13): [True: 3, False: 24]
766
24
            return Ok(None); // Not currently running.
767
        };
768
769
3
        let Some(tx) = self.operation_id_to_awaited_action.get(operation_id) else {
  Branch (769:13): [True: 0, False: 0]
  Branch (769:13): [Folded - Ignored]
  Branch (769:13): [True: 3, False: 0]
770
0
            return Err(make_err!(
771
0
                Code::Internal,
772
0
                "operation_id_to_awaited_action and action_info_hash_key_to_awaited_action are out of sync for {unique_key:?} - {operation_id}"
773
0
            ));
774
        };
775
776
0
        error_if!(
777
3
            tx.borrow().state().stage.is_finished(),
  Branch (777:13): [True: 0, False: 0]
  Branch (777:13): [Folded - Ignored]
  Branch (777:13): [True: 0, False: 3]
778
            "Tried to subscribe to a completed action but it already finished. This should never happen. {:?}",
779
0
            tx.borrow()
780
        );
781
782
3
        let maybe_connected_clients = self
783
3
            .connected_clients_for_operation_id
784
3
            .get_mut(operation_id);
785
3
        let Some(connected_clients) = maybe_connected_clients else {
  Branch (785:13): [True: 0, False: 0]
  Branch (785:13): [Folded - Ignored]
  Branch (785:13): [True: 3, False: 0]
786
0
            return Err(make_err!(
787
0
                Code::Internal,
788
0
                "connected_clients_for_operation_id and operation_id_to_awaited_action are out of sync for {unique_key:?} - {operation_id}"
789
0
            ));
790
        };
791
3
        *connected_clients += 1;
792
3
793
3
        // Immediately mark the keep alive, we don't need to wake anyone
794
3
        // so we always fake that it was not actually changed.
795
3
        // Failing update the client could lead to the client connecting
796
3
        // then not updating the keep alive in time, resulting in the
797
3
        // operation timing out due to async behavior.
798
3
        tx.send_if_modified(|awaited_action| {
799
3
            awaited_action.update_client_keep_alive((self.now_fn)().now());
800
3
            false
801
3
        });
802
3
        let subscription = tx.subscribe();
803
3
804
3
        self.client_operation_to_awaited_action
805
3
            .insert(
806
3
                client_operation_id.clone(),
807
3
                Arc::new(ClientAwaitedAction::new(
808
3
                    operation_id.clone(),
809
3
                    self.action_event_tx.clone(),
810
3
                )),
811
3
            )
812
3
            .await;
813
814
3
        Ok(Some(MemoryAwaitedActionSubscriber::new_with_client(
815
3
            subscription,
816
3
            client_operation_id.clone(),
817
3
            self.action_event_tx.clone(),
818
3
            self.now_fn.clone(),
819
3
        )))
820
27
    }
821
}
822
823
#[derive(Debug, MetricsComponent)]
824
pub struct MemoryAwaitedActionDb<I: InstantWrapper, NowFn: Fn() -> I> {
825
    #[metric]
826
    inner: Arc<Mutex<AwaitedActionDbImpl<I, NowFn>>>,
827
    tasks_change_notify: Arc<Notify>,
828
    _handle_awaited_action_events: JoinHandleDropGuard<()>,
829
}
830
831
impl<I: InstantWrapper, NowFn: Fn() -> I + Clone + Send + Sync + 'static>
832
    MemoryAwaitedActionDb<I, NowFn>
833
{
834
20
    pub fn new(
835
20
        eviction_config: &EvictionPolicy,
836
20
        tasks_change_notify: Arc<Notify>,
837
20
        now_fn: NowFn,
838
20
    ) -> Self {
839
20
        let (action_event_tx, mut action_event_rx) = mpsc::unbounded_channel();
840
20
        let inner = Arc::new(Mutex::new(AwaitedActionDbImpl {
841
20
            client_operation_to_awaited_action: EvictingMap::new(eviction_config, (now_fn)()),
842
20
            operation_id_to_awaited_action: BTreeMap::new(),
843
20
            action_info_hash_key_to_awaited_action: HashMap::new(),
844
20
            sorted_action_info_hash_keys: SortedAwaitedActions::default(),
845
20
            connected_clients_for_operation_id: HashMap::new(),
846
20
            action_event_tx,
847
20
            now_fn,
848
20
        }));
849
20
        let weak_inner = Arc::downgrade(&inner);
850
20
        Self {
851
20
            inner,
852
20
            tasks_change_notify,
853
20
            _handle_awaited_action_events: spawn!("handle_awaited_action_events", async move {
854
20
                let mut dropped_operation_ids = Vec::with_capacity(MAX_ACTION_EVENTS_RX_PER_CYCLE);
855
                loop {
856
75
                    dropped_operation_ids.clear();
857
75
                    action_event_rx
858
75
                        .recv_many(&mut dropped_operation_ids, MAX_ACTION_EVENTS_RX_PER_CYCLE)
859
75
                        .await;
860
55
                    let Some(inner) = weak_inner.upgrade() else {
  Branch (860:25): [True: 0, False: 0]
  Branch (860:25): [Folded - Ignored]
  Branch (860:25): [True: 55, False: 0]
861
0
                        return; // Nothing to cleanup, our struct is dropped.
862
                    };
863
55
                    let mut inner = inner.lock().await;
864
55
                    inner
865
55
                        .handle_action_events(dropped_operation_ids.drain(..))
866
55
                        .await;
867
                }
868
0
            }),
869
        }
870
20
    }
871
}
872
873
impl<I: InstantWrapper, NowFn: Fn() -> I + Clone + Send + Sync + 'static> AwaitedActionDb
874
    for MemoryAwaitedActionDb<I, NowFn>
875
{
876
    type Subscriber = MemoryAwaitedActionSubscriber<I, NowFn>;
877
878
3
    async fn get_awaited_action_by_id(
879
3
        &self,
880
3
        client_operation_id: &OperationId,
881
3
    ) -> Result<Option<Self::Subscriber>, Error> {
882
3
        self.inner
883
3
            .lock()
884
3
            .await
885
3
            .get_awaited_action_by_id(client_operation_id)
886
3
            .await
887
3
    }
888
889
0
    async fn get_all_awaited_actions(
890
0
        &self,
891
0
    ) -> Result<impl Stream<Item = Result<Self::Subscriber, Error>>, Error> {
892
0
        Ok(ChunkedStream::new(
893
0
            Bound::Unbounded,
894
0
            Bound::Unbounded,
895
0
            move |start, end, mut output| async move {
896
0
                let inner = self.inner.lock().await;
897
0
                let mut maybe_new_start = None;
898
899
0
                for (operation_id, item) in
900
0
                    inner.get_awaited_actions_range(start.as_ref(), end.as_ref())
901
0
                {
902
0
                    output.push_back(item);
903
0
                    maybe_new_start = Some(operation_id);
904
0
                }
905
906
0
                Ok(maybe_new_start
907
0
                    .map(|new_start| ((Bound::Excluded(new_start.clone()), end), output)))
908
0
            },
909
        ))
910
0
    }
911
912
40
    async fn get_by_operation_id(
913
40
        &self,
914
40
        operation_id: &OperationId,
915
40
    ) -> Result<Option<Self::Subscriber>, Error> {
916
40
        Ok(self.inner.lock().await.get_by_operation_id(operation_id))
917
40
    }
918
919
590
    async fn get_range_of_actions(
920
590
        &self,
921
590
        state: SortedAwaitedActionState,
922
590
        start: Bound<SortedAwaitedAction>,
923
590
        end: Bound<SortedAwaitedAction>,
924
590
        desc: bool,
925
590
    ) -> Result<impl Stream<Item = Result<Self::Subscriber, Error>> + Send, Error> {
926
590
        Ok(ChunkedStream::new(
927
590
            start,
928
590
            end,
929
1.13k
            move |start, end, mut output| async move {
930
1.13k
                let inner = self.inner.lock().await;
931
1.13k
                let mut done = true;
932
1.13k
                let mut new_start = start.as_ref();
933
1.13k
                let mut new_end = end.as_ref();
934
1.13k
935
1.13k
                let iterator = inner
936
1.13k
                    .get_range_of_actions(state, (start.as_ref(), end.as_ref()))
937
1.13k
                    .map(|res| 
res.err_tip543
(||
"In AwaitedActionDb::get_range_of_actions"0
));
938
939
                // TODO(aaronmondal) This should probably use the `.left()/right()` pattern,
940
                // but that doesn't exist in the std or any libraries we use.
941
1.13k
                if desc {
  Branch (941:20): [True: 0, False: 0]
  Branch (941:20): [Folded - Ignored]
  Branch (941:20): [True: 130, False: 1.00k]
942
130
                    for 
result43
in iterator.rev() {
943
43
                        let (sorted_awaited_action, item) =
944
43
                            result.err_tip(|| 
"In AwaitedActionDb::get_range_of_actions"0
)
?0
;
945
43
                        output.push_back(item);
946
43
                        new_end = Bound::Excluded(sorted_awaited_action);
947
43
                        done = false;
948
                    }
949
                } else {
950
1.50k
                    for 
result500
in iterator {
951
500
                        let (sorted_awaited_action, item) =
952
500
                            result.err_tip(|| 
"In AwaitedActionDb::get_range_of_actions"0
)
?0
;
953
500
                        output.push_back(item);
954
500
                        new_start = Bound::Excluded(sorted_awaited_action);
955
500
                        done = false;
956
                    }
957
                }
958
1.13k
                if done {
  Branch (958:20): [True: 0, False: 0]
  Branch (958:20): [Folded - Ignored]
  Branch (958:20): [True: 590, False: 540]
959
590
                    return Ok(None);
960
540
                }
961
540
                Ok(Some(((new_start.cloned(), new_end.cloned()), output)))
962
2.26k
            },
963
        ))
964
590
    }
965
966
39
    async fn update_awaited_action(&self, new_awaited_action: AwaitedAction) -> Result<(), Error> {
967
39
        self.inner
968
39
            .lock()
969
39
            .await
970
39
            .update_awaited_action(new_awaited_action)
?0
;
971
39
        self.tasks_change_notify.notify_one();
972
39
        Ok(())
973
39
    }
974
975
27
    async fn add_action(
976
27
        &self,
977
27
        client_operation_id: OperationId,
978
27
        action_info: Arc<ActionInfo>,
979
27
    ) -> Result<Self::Subscriber, Error> {
980
27
        let subscriber = self
981
27
            .inner
982
27
            .lock()
983
27
            .await
984
27
            .add_action(client_operation_id, action_info)
985
27
            .await
?0
;
986
27
        self.tasks_change_notify.notify_one();
987
27
        Ok(subscriber)
988
27
    }
989
}