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

getdozer / dozer / 5831539996

pending completion
5831539996

Pull #1824

github

chubei
feat: Publish DAG to JSON
Pull Request #1824: feat: Publish Source contracts as JSON file

249 of 249 new or added lines in 14 files covered. (100.0%)

45567 of 61724 relevant lines covered (73.82%)

56287.38 hits per line

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

54.12
/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::ApiServeFailed))
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
                tokio::spawn(async move {
6✔
141
                    grpc_server
6✔
142
                        .run(cache_endpoints, shutdown, operations_receiver)
6✔
143
                        .await
12✔
144
                        .map_err(OrchestrationError::ApiInitFailed)
6✔
145
                })
6✔
146
            } else {
×
147
                tokio::spawn(async move { Ok::<(), OrchestrationError>(()) })
×
148
            };
149

×
150
            futures.push(flatten_join_handle(rest_handle));
6✔
151
            futures.push(flatten_join_handle(grpc_handle));
6✔
152

×
153
            while let Some(result) = futures.next().await {
24✔
154
                result?;
18✔
155
            }
×
156

×
157
            Ok::<(), OrchestrationError>(())
6✔
158
        })?;
6✔
159

×
160
        Ok(())
6✔
161
    }
6✔
162

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

×
181
        let app_grpc_config = get_app_grpc_config(&self.config);
6✔
182
        let internal_server_future = start_internal_pipeline_server(
6✔
183
            executor.endpoint_and_logs().to_vec(),
6✔
184
            &app_grpc_config,
6✔
185
            shutdown.create_shutdown_future(),
6✔
186
        );
6✔
187

×
188
        if let Some(api_notifier) = api_notifier {
6✔
189
            api_notifier
6✔
190
                .send(true)
6✔
191
                .expect("Failed to notify API server");
6✔
192
        }
6✔
193

×
194
        let running = shutdown.get_running_flag();
6✔
195
        let pipeline_future = self
6✔
196
            .runtime
6✔
197
            .spawn_blocking(|| run_dag_executor(dag_executor, running));
6✔
198

6✔
199
        let mut futures = FuturesUnordered::new();
6✔
200
        futures.push(
6✔
201
            internal_server_future
6✔
202
                .map_err(OrchestrationError::InternalServerFailed)
6✔
203
                .boxed(),
6✔
204
        );
6✔
205
        futures.push(flatten_join_handle(pipeline_future).boxed());
6✔
206

6✔
207
        self.runtime.block_on(async move {
6✔
208
            while let Some(result) = futures.next().await {
24✔
209
                result?;
12✔
210
            }
×
211
            Ok(())
6✔
212
        })
6✔
213
    }
6✔
214

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

227
            Ok(schema_map)
×
228
        })
×
229
    }
×
230

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

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

6✔
251
        info!(
6✔
252
            "Initiating app: {}",
×
253
            get_colored_text(&self.config.app_name, PURPLE)
×
254
        );
×
255
        if force {
6✔
256
            self.clean()?;
×
257
        }
6✔
258
        validate_config(&self.config)?;
6✔
259

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

×
279
        // Get current contract.
×
280
        let enable_token = self
6✔
281
            .config
6✔
282
            .api
6✔
283
            .as_ref()
6✔
284
            .map(|api| api.api_security.is_some())
6✔
285
            .unwrap_or(false);
6✔
286
        let enable_on_event = self
6✔
287
            .config
6✔
288
            .flags
6✔
289
            .as_ref()
6✔
290
            .map(|flags| flags.push_events)
6✔
291
            .unwrap_or(false);
6✔
292
        let contract = build::Contract::new(
6✔
293
            dag_schemas,
6✔
294
            &self.config.endpoints,
6✔
295
            enable_token,
6✔
296
            enable_on_event,
6✔
297
        )?;
6✔
298

×
299
        // Run build
×
300
        let storage_config = get_log_options(&self.config).storage_config;
6✔
301
        self.runtime
6✔
302
            .block_on(build::build(&home_dir, &contract, &storage_config))?;
6✔
303

×
304
        Ok(())
6✔
305
    }
6✔
306

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

×
316
        let home_dir = PathBuf::from(self.config.home_dir.clone());
×
317
        if home_dir.exists() {
×
318
            fs::remove_dir_all(&home_dir)
×
319
                .map_err(|e| ExecutionError::FileSystemError(home_dir, e))?;
×
320
        };
×
321

×
322
        Ok(())
×
323
    }
×
324

×
325
    pub fn run_all(&mut self, shutdown: ShutdownReceiver) -> Result<(), OrchestrationError> {
6✔
326
        let shutdown_api = shutdown.clone();
6✔
327

6✔
328
        let mut dozer_api = self.clone();
6✔
329

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

6✔
332
        self.build(false)?;
6✔
333

×
334
        let mut dozer_pipeline = self.clone();
6✔
335
        let pipeline_thread = thread::spawn(move || dozer_pipeline.run_apps(shutdown, Some(tx)));
6✔
336

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

6✔
349
        dozer_api.run_api(shutdown_api)?;
6✔
350

×
351
        // wait for pipeline thread to shutdown gracefully
×
352
        pipeline_thread.join().unwrap()
6✔
353
    }
6✔
354
}
×
355

×
356
pub fn validate_sql(sql: String) -> Result<(), PipelineError> {
×
357
    statement_to_pipeline(&sql, &mut AppPipeline::new(), None).map_or_else(
×
358
        |e| {
×
359
            error!(
×
360
                "[sql][{}] Transforms validation error: {}",
×
361
                get_colored_text("X", RED),
×
362
                e
×
363
            );
×
364
            Err(e)
×
365
        },
×
366
        |_| {
×
367
            info!(
×
368
                "[sql][{}]  Transforms validation completed",
×
369
                get_colored_text("✓", GREEN)
×
370
            );
×
371
            Ok(())
×
372
        },
×
373
    )
×
374
}
×
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