common_procedure/
watcher.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
// Copyright 2023 Greptime Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use common_telemetry::debug;
use snafu::ResultExt;
use tokio::sync::watch::Receiver;

use crate::error::{ProcedureExecSnafu, Result, WaitWatcherSnafu};
use crate::procedure::{Output, ProcedureState};

/// Watcher to watch procedure state.
pub type Watcher = Receiver<ProcedureState>;

/// Wait the [Watcher] until the [ProcedureState] is done.
pub async fn wait(watcher: &mut Watcher) -> Result<Option<Output>> {
    loop {
        watcher.changed().await.context(WaitWatcherSnafu)?;
        match &*watcher.borrow() {
            ProcedureState::Running => (),
            ProcedureState::Done { output } => {
                return Ok(output.clone());
            }
            ProcedureState::Failed { error } => {
                return Err(error.clone()).context(ProcedureExecSnafu);
            }
            ProcedureState::Retrying { error } => {
                debug!("retrying, source: {}", error)
            }
            ProcedureState::RollingBack { error } => {
                debug!("rolling back, source: {:?}", error)
            }
            ProcedureState::PrepareRollback { error } => {
                debug!("commit rollback, source: {}", error)
            }
        }
    }
}

#[cfg(test)]
mod tests {

    use std::sync::Arc;
    use std::time::Duration;

    use async_trait::async_trait;
    use common_error::mock::MockError;
    use common_error::status_code::StatusCode;
    use common_test_util::temp_dir::create_temp_dir;

    use super::*;
    use crate::error::Error;
    use crate::local::{test_util, LocalManager, ManagerConfig};
    use crate::store::state_store::ObjectStateStore;
    use crate::{
        Context, LockKey, Procedure, ProcedureId, ProcedureManager, ProcedureWithId, Status,
    };

    #[tokio::test]
    async fn test_success_after_retry() {
        let dir = create_temp_dir("after_retry");
        let config = ManagerConfig {
            parent_path: "data/".to_string(),
            max_retry_times: 3,
            retry_delay: Duration::from_millis(500),
            ..Default::default()
        };
        let state_store = Arc::new(ObjectStateStore::new(test_util::new_object_store(&dir)));
        let manager = LocalManager::new(config, state_store);
        manager.start().await.unwrap();

        #[derive(Debug)]
        struct MockProcedure {
            error: bool,
        }

        #[async_trait]
        impl Procedure for MockProcedure {
            fn type_name(&self) -> &str {
                "MockProcedure"
            }

            async fn execute(&mut self, _ctx: &Context) -> Result<Status> {
                if self.error {
                    self.error = !self.error;
                    Err(Error::retry_later(MockError::new(StatusCode::Internal)))
                } else {
                    Ok(Status::done_with_output("hello"))
                }
            }

            fn dump(&self) -> Result<String> {
                Ok(String::new())
            }

            fn lock_key(&self) -> LockKey {
                LockKey::single_exclusive("test.submit")
            }
        }

        let procedure_id = ProcedureId::random();
        let mut watcher = manager
            .submit(ProcedureWithId {
                id: procedure_id,
                procedure: Box::new(MockProcedure { error: true }),
            })
            .await
            .unwrap();

        let output = wait(&mut watcher).await.unwrap().unwrap();
        let output = output.downcast::<&str>().unwrap();
        assert_eq!(output.as_ref(), &"hello");
    }
}