• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

getdozer / dozer / 5877741187

16 Aug 2023 10:38AM UTC coverage: 77.649% (+0.04%) from 77.605%
5877741187

push

github

web-flow
fix: Don't start api until internal server is up (#1861)

49 of 49 new or added lines in 4 files covered. (100.0%)

46090 of 59357 relevant lines covered (77.65%)

41299.14 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

71.32
/dozer-cli/src/simple/orchestrator.rs
1
use super::executor::{run_dag_executor, Executor};
2
use crate::errors::OrchestrationError;
3
use crate::pipeline::PipelineBuilder;
4
use crate::shutdown::ShutdownReceiver;
5
use crate::simple::build;
6
use crate::simple::helper::validate_config;
7
use crate::utils::{
8
    get_api_security_config, get_app_grpc_config, get_cache_manager_options, get_executor_options,
9
    get_grpc_config, get_log_options, get_rest_config,
10
};
11

12
use crate::{flatten_join_handle, join_handle_map_err};
13
use dozer_api::auth::{Access, Authorizer};
14
use dozer_api::grpc::internal::internal_pipeline_server::start_internal_pipeline_server;
15
use dozer_api::{grpc, rest, CacheEndpoint};
16
use dozer_cache::cache::LmdbRwCacheManager;
17
use dozer_cache::dozer_log::home_dir::HomeDir;
18
use dozer_core::app::AppPipeline;
19
use dozer_core::dag_schemas::DagSchemas;
20

21
use crate::console_helper::get_colored_text;
22
use crate::console_helper::GREEN;
23
use crate::console_helper::PURPLE;
24
use crate::console_helper::RED;
25
use dozer_core::errors::ExecutionError;
26
use dozer_ingestion::connectors::{get_connector, SourceSchema, TableInfo};
27
use dozer_sql::pipeline::builder::statement_to_pipeline;
28
use dozer_sql::pipeline::errors::PipelineError;
29
use dozer_types::crossbeam::channel::{self, Sender};
30
use dozer_types::indicatif::{MultiProgress, ProgressDrawTarget};
31
use dozer_types::log::info;
32
use dozer_types::models::config::Config;
33
use dozer_types::tracing::error;
34
use futures::stream::FuturesUnordered;
35
use futures::{FutureExt, StreamExt, TryFutureExt};
36
use metrics::{describe_counter, describe_histogram};
37
use std::collections::HashMap;
38
use std::fs;
39
use std::path::PathBuf;
40

41
use std::sync::Arc;
42
use std::thread;
43
use tokio::runtime::Runtime;
44
use tokio::sync::broadcast;
45

46
#[derive(Clone)]
12✔
47
pub struct SimpleOrchestrator {
48
    pub config: Config,
49
    pub runtime: Arc<Runtime>,
50
    pub multi_pb: MultiProgress,
51
}
52

53
impl SimpleOrchestrator {
54
    pub fn new(config: Config, runtime: Arc<Runtime>) -> Self {
6✔
55
        let progress_draw_target = if atty::is(atty::Stream::Stderr) {
6✔
56
            ProgressDrawTarget::stderr()
×
57
        } else {
58
            ProgressDrawTarget::hidden()
6✔
59
        };
60
        Self {
6✔
61
            config,
6✔
62
            runtime,
6✔
63
            multi_pb: MultiProgress::with_draw_target(progress_draw_target),
6✔
64
        }
6✔
65
    }
6✔
66

67
    pub fn run_api(&mut self, shutdown: ShutdownReceiver) -> Result<(), OrchestrationError> {
6✔
68
        describe_histogram!(
6✔
69
            dozer_api::API_LATENCY_HISTOGRAM_NAME,
×
70
            "The api processing latency in seconds"
×
71
        );
72
        describe_counter!(
6✔
73
            dozer_api::API_REQUEST_COUNTER_NAME,
×
74
            "Number of requests processed by the api"
×
75
        );
76
        self.runtime.block_on(async {
6✔
77
            let mut futures = FuturesUnordered::new();
6✔
78

6✔
79
            // Open `RoCacheEndpoint`s. Streaming operations if necessary.
6✔
80
            let flags = self.config.flags.clone().unwrap_or_default();
6✔
81
            let (operations_sender, operations_receiver) = if flags.dynamic {
6✔
82
                let (sender, receiver) = broadcast::channel(16);
6✔
83
                (Some(sender), Some(receiver))
6✔
84
            } else {
85
                (None, None)
×
86
            };
87

88
            let internal_grpc_config = get_app_grpc_config(&self.config);
6✔
89
            let app_server_addr = format!(
6✔
90
                "http://{}:{}",
6✔
91
                internal_grpc_config.host, internal_grpc_config.port
6✔
92
            );
6✔
93
            let cache_manager = Arc::new(
6✔
94
                LmdbRwCacheManager::new(get_cache_manager_options(&self.config))
6✔
95
                    .map_err(OrchestrationError::CacheInitFailed)?,
6✔
96
            );
97
            let mut cache_endpoints = vec![];
6✔
98
            for endpoint in &self.config.endpoints {
12✔
99
                let (cache_endpoint, handle) = CacheEndpoint::new(
6✔
100
                    app_server_addr.clone(),
6✔
101
                    &*cache_manager,
6✔
102
                    endpoint.clone(),
6✔
103
                    Box::pin(shutdown.create_shutdown_future()),
6✔
104
                    operations_sender.clone(),
6✔
105
                    Some(self.multi_pb.clone()),
6✔
106
                )
6✔
107
                .await?;
54✔
108
                let cache_name = endpoint.name.clone();
6✔
109
                futures.push(flatten_join_handle(join_handle_map_err(handle, move |e| {
6✔
110
                    if e.is_map_full() {
×
111
                        OrchestrationError::CacheFull(cache_name)
×
112
                    } else {
113
                        OrchestrationError::CacheBuildFailed(cache_name, e)
×
114
                    }
115
                })));
6✔
116
                cache_endpoints.push(Arc::new(cache_endpoint));
6✔
117
            }
118

119
            // Initialize API Server
120
            let rest_config = get_rest_config(&self.config);
6✔
121
            let rest_handle = if rest_config.enabled {
6✔
122
                let security = get_api_security_config(&self.config).cloned();
6✔
123
                let cache_endpoints_for_rest = cache_endpoints.clone();
6✔
124
                let shutdown_for_rest = shutdown.create_shutdown_future();
6✔
125
                let api_server = rest::ApiServer::new(rest_config, security);
6✔
126
                let api_server = api_server
6✔
127
                    .run(cache_endpoints_for_rest, shutdown_for_rest)
6✔
128
                    .map_err(OrchestrationError::ApiInitFailed)?;
6✔
129
                tokio::spawn(api_server.map_err(OrchestrationError::RestServeFailed))
6✔
130
            } else {
131
                tokio::spawn(async move { Ok::<(), OrchestrationError>(()) })
×
132
            };
133

134
            // Initialize gRPC Server
135
            let grpc_config = get_grpc_config(&self.config);
6✔
136
            let grpc_handle = if grpc_config.enabled {
6✔
137
                let api_security = get_api_security_config(&self.config).cloned();
6✔
138
                let grpc_server = grpc::ApiServer::new(grpc_config, api_security, flags);
6✔
139
                let shutdown = shutdown.create_shutdown_future();
6✔
140
                let grpc_server = grpc_server
6✔
141
                    .run(cache_endpoints, shutdown, operations_receiver)
6✔
142
                    .await
×
143
                    .map_err(OrchestrationError::ApiInitFailed)?;
6✔
144
                tokio::spawn(async move {
6✔
145
                    grpc_server
6✔
146
                        .await
12✔
147
                        .map_err(OrchestrationError::GrpcServeFailed)
6✔
148
                })
6✔
149
            } else {
150
                tokio::spawn(async move { Ok::<(), OrchestrationError>(()) })
×
151
            };
152

153
            futures.push(flatten_join_handle(rest_handle));
6✔
154
            futures.push(flatten_join_handle(grpc_handle));
6✔
155

156
            while let Some(result) = futures.next().await {
24✔
157
                result?;
18✔
158
            }
159

160
            Ok::<(), OrchestrationError>(())
6✔
161
        })?;
6✔
162

163
        Ok(())
6✔
164
    }
6✔
165

166
    pub fn run_apps(
6✔
167
        &mut self,
6✔
168
        shutdown: ShutdownReceiver,
6✔
169
        api_notifier: Option<Sender<bool>>,
6✔
170
    ) -> Result<(), OrchestrationError> {
6✔
171
        let home_dir = HomeDir::new(self.config.home_dir.clone(), self.config.cache_dir.clone());
6✔
172
        let executor = self.runtime.block_on(Executor::new(
6✔
173
            &home_dir,
6✔
174
            &self.config.connections,
6✔
175
            &self.config.sources,
6✔
176
            self.config.sql.as_deref(),
6✔
177
            &self.config.endpoints,
6✔
178
            get_log_options(&self.config),
6✔
179
            self.multi_pb.clone(),
6✔
180
        ))?;
6✔
181
        let dag_executor = executor
6✔
182
            .create_dag_executor(self.runtime.clone(), get_executor_options(&self.config))?;
6✔
183

184
        let app_grpc_config = get_app_grpc_config(&self.config);
6✔
185
        let internal_server_future = self
6✔
186
            .runtime
6✔
187
            .block_on(start_internal_pipeline_server(
6✔
188
                executor.endpoint_and_logs().to_vec(),
6✔
189
                &app_grpc_config,
6✔
190
                shutdown.create_shutdown_future(),
6✔
191
            ))
6✔
192
            .map_err(OrchestrationError::InternalServerFailed)?;
6✔
193

194
        if let Some(api_notifier) = api_notifier {
6✔
195
            api_notifier
6✔
196
                .send(true)
6✔
197
                .expect("Failed to notify API server");
6✔
198
        }
6✔
199

200
        let running = shutdown.get_running_flag();
6✔
201
        let pipeline_future = self
6✔
202
            .runtime
6✔
203
            .spawn_blocking(|| run_dag_executor(dag_executor, running));
6✔
204

6✔
205
        let mut futures = FuturesUnordered::new();
6✔
206
        futures.push(
6✔
207
            internal_server_future
6✔
208
                .map_err(OrchestrationError::GrpcServeFailed)
6✔
209
                .boxed(),
6✔
210
        );
6✔
211
        futures.push(flatten_join_handle(pipeline_future).boxed());
6✔
212

6✔
213
        self.runtime.block_on(async move {
6✔
214
            while let Some(result) = futures.next().await {
24✔
215
                result?;
12✔
216
            }
217
            Ok(())
6✔
218
        })
6✔
219
    }
6✔
220

221
    #[allow(clippy::type_complexity)]
222
    pub fn list_connectors(
×
223
        &self,
×
224
    ) -> Result<HashMap<String, (Vec<TableInfo>, Vec<SourceSchema>)>, OrchestrationError> {
×
225
        self.runtime.block_on(async {
×
226
            let mut schema_map = HashMap::new();
×
227
            for connection in &self.config.connections {
×
228
                let connector = get_connector(connection.clone())?;
×
229
                let schema_tuples = connector.list_all_schemas().await?;
×
230
                schema_map.insert(connection.name.clone(), schema_tuples);
×
231
            }
232

233
            Ok(schema_map)
×
234
        })
×
235
    }
×
236

237
    pub fn generate_token(&self) -> Result<String, OrchestrationError> {
238
        if let Some(api_config) = &self.config.api {
×
239
            if let Some(api_security) = &api_config.api_security {
×
240
                match api_security {
×
241
                    dozer_types::models::api_security::ApiSecurity::Jwt(secret) => {
×
242
                        let auth = Authorizer::new(secret, None, None);
×
243
                        let token = auth
×
244
                            .generate_token(Access::All, None)
×
245
                            .map_err(OrchestrationError::GenerateTokenFailed)?;
×
246
                        return Ok(token);
×
247
                    }
248
                }
249
            }
×
250
        }
×
251
        Err(OrchestrationError::MissingSecurityConfig)
×
252
    }
×
253

254
    pub fn build(&mut self, force: bool) -> Result<(), OrchestrationError> {
6✔
255
        let home_dir = HomeDir::new(self.config.home_dir.clone(), self.config.cache_dir.clone());
6✔
256

6✔
257
        info!(
6✔
258
            "Initiating app: {}",
×
259
            get_colored_text(&self.config.app_name, PURPLE)
×
260
        );
261
        if force {
6✔
262
            self.clean()?;
×
263
        }
6✔
264
        validate_config(&self.config)?;
6✔
265

266
        // Calculate schemas.
267
        let endpoint_and_logs = self
6✔
268
            .config
6✔
269
            .endpoints
6✔
270
            .iter()
6✔
271
            // We're not really going to run the pipeline, so we don't create logs.
6✔
272
            .map(|endpoint| (endpoint.clone(), None))
6✔
273
            .collect();
6✔
274
        let builder = PipelineBuilder::new(
6✔
275
            &self.config.connections,
6✔
276
            &self.config.sources,
6✔
277
            self.config.sql.as_deref(),
6✔
278
            endpoint_and_logs,
6✔
279
            self.multi_pb.clone(),
6✔
280
        );
6✔
281
        let dag = builder.build(self.runtime.clone())?;
6✔
282
        // Populate schemas.
283
        let dag_schemas = DagSchemas::new(dag)?;
6✔
284

285
        // Get current contract.
286
        let enable_token = self
6✔
287
            .config
6✔
288
            .api
6✔
289
            .as_ref()
6✔
290
            .map(|api| api.api_security.is_some())
6✔
291
            .unwrap_or(false);
6✔
292
        let enable_on_event = self
6✔
293
            .config
6✔
294
            .flags
6✔
295
            .as_ref()
6✔
296
            .map(|flags| flags.push_events)
6✔
297
            .unwrap_or(false);
6✔
298
        let contract = build::Contract::new(
6✔
299
            dag_schemas,
6✔
300
            &self.config.endpoints,
6✔
301
            enable_token,
6✔
302
            enable_on_event,
6✔
303
        )?;
6✔
304

305
        // Run build
306
        let storage_config = get_log_options(&self.config).storage_config;
6✔
307
        self.runtime
6✔
308
            .block_on(build::build(&home_dir, &contract, &storage_config))?;
6✔
309

310
        Ok(())
6✔
311
    }
6✔
312

313
    // Cleaning the entire folder as there will be inconsistencies
314
    // between pipeline, cache and generated proto files.
315
    pub fn clean(&mut self) -> Result<(), OrchestrationError> {
×
316
        let cache_dir = PathBuf::from(self.config.cache_dir.clone());
×
317
        if cache_dir.exists() {
×
318
            fs::remove_dir_all(&cache_dir)
×
319
                .map_err(|e| ExecutionError::FileSystemError(cache_dir, e))?;
×
320
        };
×
321

322
        let home_dir = PathBuf::from(self.config.home_dir.clone());
×
323
        if home_dir.exists() {
×
324
            fs::remove_dir_all(&home_dir)
×
325
                .map_err(|e| ExecutionError::FileSystemError(home_dir, e))?;
×
326
        };
×
327

328
        Ok(())
×
329
    }
×
330

331
    pub fn run_all(&mut self, shutdown: ShutdownReceiver) -> Result<(), OrchestrationError> {
6✔
332
        let shutdown_api = shutdown.clone();
6✔
333

6✔
334
        let mut dozer_api = self.clone();
6✔
335

6✔
336
        let (tx, rx) = channel::unbounded::<bool>();
6✔
337

6✔
338
        self.build(false)?;
6✔
339

340
        let mut dozer_pipeline = self.clone();
6✔
341
        let pipeline_thread = thread::spawn(move || dozer_pipeline.run_apps(shutdown, Some(tx)));
6✔
342

6✔
343
        // Wait for pipeline to initialize caches before starting api server
6✔
344
        if rx.recv().is_err() {
6✔
345
            // This means the pipeline thread returned before sending a message. Either an error happened or it panicked.
346
            return match pipeline_thread.join() {
×
347
                Ok(Err(e)) => Err(e),
×
348
                Ok(Ok(())) => panic!("An error must have happened"),
×
349
                Err(e) => {
×
350
                    std::panic::panic_any(e);
×
351
                }
352
            };
353
        }
6✔
354

6✔
355
        dozer_api.run_api(shutdown_api)?;
6✔
356

357
        // wait for pipeline thread to shutdown gracefully
358
        pipeline_thread.join().unwrap()
6✔
359
    }
6✔
360
}
361

362
pub fn validate_sql(sql: String) -> Result<(), PipelineError> {
×
363
    statement_to_pipeline(&sql, &mut AppPipeline::new(), None).map_or_else(
×
364
        |e| {
×
365
            error!(
×
366
                "[sql][{}] Transforms validation error: {}",
×
367
                get_colored_text("X", RED),
×
368
                e
×
369
            );
×
370
            Err(e)
×
371
        },
×
372
        |_| {
×
373
            info!(
×
374
                "[sql][{}]  Transforms validation completed",
×
375
                get_colored_text("✓", GREEN)
×
376
            );
377
            Ok(())
×
378
        },
×
379
    )
×
380
}
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc