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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
//! 应用程序配置
use std::future::Future;
use std::{
    any::{type_name, Any, TypeId},
    fmt::Debug,
};

use crate::tina::config::{log::LogConfig, ConfigExt, UpdateableConfig};
use crate::tina::config::{security::SecurityConfig, server::ServerConfig};
use crate::tina::core::service::cache::ICacheService;
use crate::tina::core::service::date_time::IDateTimeService;
use crate::tina::core::service::dict::IDictService;
use crate::tina::core::service::file::IFileService;
use crate::tina::core::service::log_record::ILogRecordService;
use crate::tina::core::service::operation_log::IOperationLogService;
use crate::tina::core::service::permission::IPermissionService;
use crate::tina::core::service::throttle::IThrottleService;
use crate::tina::core::service::user::IUserService;
use crate::tina::data::AppResult;
use crate::tina::security::password_encoder::PasswordEncoder;
use crate::tina::util::Utility;
use crate::tina::{client::registry::RegistryClient, config::registry::RegistryConfig};
use crate::{app_error_from, app_system_error};
use config::builder::DefaultState;
use config::{Config, ConfigBuilder};
use dashmap::DashMap;
use futures_util::future::BoxFuture;
use futures_util::FutureExt;
use reqwest::Client;
use reqwest_middleware::ClientWithMiddleware;
use serde::{Deserialize, Serialize, Serializer};
use std::ops::Deref;
use std::sync::Arc;
use std::time::Duration;

/// 应用程序配置
#[derive(Clone)]
pub struct Application(Arc<AppConfig>);

impl From<AppConfig> for Application {
    fn from(config: AppConfig) -> Self {
        Application(Arc::new(config))
    }
}

impl From<Arc<AppConfig>> for Application {
    fn from(config: Arc<AppConfig>) -> Self {
        Application(config)
    }
}

impl Debug for Application {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("Application").finish()
    }
}

impl Deref for Application {
    type Target = AppConfig;

    fn deref(&self) -> &Self::Target {
        self.0.deref()
    }
}

impl AsRef<Application> for Application {
    fn as_ref(&self) -> &Application {
        self
    }
}

/// 应用程序配置扩展类型
pub type AppConfigExtention = Arc<dyn Any + Send + Sync + 'static>;

/// 注册中心消息
#[derive(Debug)]
pub struct AppConfigExtentionMessage {
    /// 事件
    pub event: AppConfigEvent,
    /// 扩展
    pub extension: Option<(TypeId, AppConfigExtention)>,
}

/// 注册中心消息事件
#[derive(Debug, Clone, Copy)]
pub enum AppConfigEvent {
    /// 中断
    Terminate,
    /// 改变扩展
    ExtensionChange,
}

/// 注册中心配置变更处理
pub type AppConfigRegistryConfigChangeFunc = Arc<dyn Fn(Config) -> BoxFuture<'static, AppResult<()>> + Send + Sync + 'static>;

/// 应用程序配置
#[allow(unused)]
#[derive(Serialize, Deserialize)]
pub struct AppConfig {
    /// 应用程序监听地址
    pub address: String,
    /// 应用程序监听端口
    pub port: Option<usize>,
    /// 应用程序的业务线程数
    pub workers: usize,
    /// 应用名称
    pub application_name: String,
    /// 版本
    pub version: String,
    /// 版权年份
    pub copyright_year: String,
    /// 启动后停止(用于测试)
    pub shutdown_after_start: Option<bool>,
    #[serde(skip)]
    extensions: Arc<DashMap<TypeId, AppConfigExtention>>,
    #[serde(skip)]
    /// Http 客户端
    pub http_client: Option<ClientWithMiddleware>,
    #[serde(skip)]
    pub(crate) registry_config_change_fn: Option<AppConfigRegistryConfigChangeFunc>,
}

impl Debug for AppConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AppConfig")
            .field("address", &self.address)
            .field("port", &self.port)
            .field("workers", &self.workers)
            .field("application_name", &self.application_name)
            .field("version", &self.version)
            .field("copyright_year", &self.copyright_year)
            .field("extensions", &self.extensions)
            .finish()
    }
}

impl AppConfig {
    /// 设置应用程序监听地址
    pub fn address(mut self, address: &str) -> Self {
        self.address = address.to_owned();
        self
    }
    /// 设置应用程序监听端口
    pub fn port(mut self, port: usize) -> Self {
        self.port = Some(port);
        self
    }
    /// 设置应用程序业务线程数
    pub fn workers(mut self, workers: usize) -> Self {
        self.workers = workers;
        self
    }
    /// 设置应用名称
    pub fn application_name(mut self, application_name: &str) -> Self {
        self.application_name = application_name.to_owned();
        self
    }
    /// 设置版本
    pub fn version(mut self, version: &str) -> Self {
        self.version = version.to_owned();
        self
    }
    /// 设置版权年份
    pub fn copyright_year(mut self, copyright_year: &str) -> Self {
        self.copyright_year = copyright_year.to_owned();
        self
    }
    /// 设置Http客户端
    pub fn http_client(mut self, http_client: ClientWithMiddleware) -> Self {
        self.http_client = Some(http_client);
        self
    }
}

impl Default for AppConfig {
    fn default() -> Self {
        Self::new()
    }
}

impl AppConfig {
    /// 构建配置
    pub fn new() -> AppConfig {
        AppConfig {
            address: "0.0.0.0".to_string(),
            port: None,
            workers: 50,
            application_name: "".to_owned(),
            version: "1.0.0".to_string(),
            copyright_year: "2023".to_string(),
            extensions: Default::default(),
            http_client: Some(ClientWithMiddleware::from(Client::default())),
            registry_config_change_fn: None,
            shutdown_after_start: None,
        }
    }
    /// 从Yaml内容构建
    pub fn from_yaml_content(content: impl AsRef<str>) -> AppResult<(Self, Config)> {
        let config = ConfigBuilder::<DefaultState>::default()
            .add_source(config::File::from_str(content.as_ref(), config::FileFormat::Yaml))
            .build()
            .map_err(app_error_from!())?;
        Self::from_config(config)
    }
    /// 从Config构建
    pub fn from_config(config: Config) -> AppResult<(Self, Config)> {
        let app = config.clone().try_deserialize::<Self>().map_err(app_error_from!())?;
        Ok((app, config))
    }
    /// 获取应用程序扩展
    pub fn extension<T: Send + Sync + 'static>(&self) -> AppResult<Arc<T>> {
        let type_id = TypeId::of::<T>();
        match self.extensions.get(&type_id) {
            None => Err(crate::app_system_error!("no type found in extension: {}", type_name::<T>())),
            Some(ext) => ext
                .clone()
                .downcast::<T>()
                .map_err(|err| crate::app_system_error!("cast extension type failed: {}, reason: {:?}", type_name::<T>(), err)),
        }
    }
    /// 添加应用程序扩展
    pub fn add_extension<T: Send + Sync + 'static>(&self, ext: T) {
        let type_id = TypeId::of::<T>();
        self.extensions.insert(type_id, Arc::new(ext));
    }
    /// 程序是否终止标记
    pub fn is_terminated(&self) -> bool {
        Utility::is_terminated()
    }
    /// 设置程序终止标记
    pub fn terminate(&self) {
        Utility::terminate()
    }
    /// 获取Http Client
    pub fn get_http_client(&self) -> AppResult<&ClientWithMiddleware> {
        self.http_client.as_ref().ok_or_else(|| app_system_error!("no http client found in application"))
    }
    /// 初始化默认配置
    async fn init_default_config(&mut self, config0: &Config) -> AppResult<()> {
        let config = config0.get_or_default::<LogConfig>("log");
        config.apply(self).await?;
        self.set_config(config);
        let config = config0.get_or_default::<RegistryConfig>("registry");
        config.apply(self).await?;
        self.set_config(config);
        let config = config0.get_or_default::<SecurityConfig>("security");
        config.apply(self).await?;
        self.set_config(config);
        let config = config0.get_or_default::<ServerConfig>("server");
        config.apply(self).await?;
        self.set_config(config);
        Ok(())
    }
    /// 更新默认配置
    pub(crate) async fn update_default_config(&self, config: &Config) -> AppResult<()> {
        if let Ok(v) = config.get::<LogConfig>("log") {
            tracing::info!("更新配置[{}]: {:?}", type_name::<LogConfig>(), v);
            v.apply(self).await?;
            self.set_config(v)
        }
        if let Ok(v) = config.get::<RegistryConfig>("registry") {
            tracing::info!("更新配置[{}]: {:?}", type_name::<RegistryConfig>(), v);
            v.apply(self).await?;
            self.set_config(v)
        }
        if let Ok(v) = config.get::<SecurityConfig>("security") {
            tracing::info!("更新配置[{}]: {:?}", type_name::<SecurityConfig>(), v);
            v.apply(self).await?;
            self.set_config(v)
        }
        if let Ok(v) = config.get::<ServerConfig>("server") {
            tracing::info!("更新配置[{}]: {:?}", type_name::<ServerConfig>(), v);
            v.apply(self).await?;
            self.set_config(v)
        }
        Ok(())
    }
    /// 更新配置
    pub async fn update_config<T: for<'de> Deserialize<'de> + UpdateableConfig + Debug + Send + Sync + 'static>(
        &self,
        config: &Config,
        root_key: &str,
    ) -> AppResult<()> {
        if let Ok(v) = config.get::<T>(root_key) {
            tracing::info!("更新配置[{}]: {:?}", type_name::<ServerConfig>(), v);
            v.apply(self).await?;
            self.set_config(v)
        }
        Ok(())
    }
    /// 初始化
    pub async fn init(mut self, config: &Config) -> AppResult<Application> {
        self.init_default_config(config).await?;
        self.set_password_encoder(PasswordEncoder::try_new()?);
        #[cfg(feature = "client-grpc")]
        {
            self.add_extension(crate::tina::client::GrpcClient::default());
        }

        let application = Application::from(self);
        #[cfg(feature = "client-nacos")]
        {
            if let Err(err) = application.regist_client() {
                tracing::error!("注册客户端失败...{err:?}");
                return Err(err);
            }
        }
        Ok(application)
    }
    /// 设置配置变更逻辑
    pub fn with_config_change<F, R>(&mut self, f: F) -> &mut Self
    where
        F: Fn(Config) -> R + Send + Sync + 'static,
        R: Future<Output = AppResult<()>> + Send + 'static,
    {
        let func = move |config: Config| f(config).boxed();
        self.registry_config_change_fn = Some(Arc::new(func) as AppConfigRegistryConfigChangeFunc);
        self
    }
}

impl AppConfig {
    /// 设置密码处理器
    pub fn set_password_encoder(&mut self, encoder: PasswordEncoder) {
        self.add_extension(encoder)
    }
    /// 获取登录服务
    pub fn get_password_encoder(&self) -> AppResult<Arc<PasswordEncoder>> {
        self.extension::<PasswordEncoder>()
    }
    /// 设置服务
    pub fn set_service<S: Send + Sync + ?Sized + 'static>(&mut self, service: Arc<S>) {
        let type_id = TypeId::of::<Arc<S>>();
        self.extensions.insert(type_id, Arc::new(service));
    }
    /// 获取登录服务
    pub fn get_service<S: Send + Sync + ?Sized + 'static>(&self) -> AppResult<Arc<S>> {
        let type_id = TypeId::of::<Arc<S>>();
        match self.extensions.get(&type_id) {
            None => Err(app_system_error!("no {} service init in application", type_name::<Arc<S>>())),
            Some(service) => match service.downcast_ref::<Arc<S>>() {
                None => Err(app_system_error!("no {} service init in application", type_name::<Arc<S>>())),
                Some(service) => Ok(service.clone()),
            },
        }
    }
    /// 设置权限服务
    pub fn set_permission_service(&mut self, service: impl IPermissionService) {
        self.set_service(Arc::new(service) as Arc<dyn IPermissionService>)
    }
    /// 获取权限服务
    pub fn get_permission_service(&self) -> AppResult<Arc<dyn IPermissionService>> {
        self.get_service::<dyn IPermissionService>()
    }
    /// 设置用户服务
    pub fn set_user_service(&mut self, service: impl IUserService) {
        self.set_service(Arc::new(service) as Arc<dyn IUserService>)
    }
    /// 获取用户服务
    pub fn get_user_service(&self) -> AppResult<Arc<dyn IUserService>> {
        self.get_service::<dyn IUserService>()
    }
    /// 设置后台异步服务
    pub fn set_operation_log_service(&mut self, service: impl IOperationLogService) {
        self.set_service(Arc::new(service) as Arc<dyn IOperationLogService>)
    }
    /// 获取后台异步服务
    pub fn get_operation_log_service(&self) -> AppResult<Arc<dyn IOperationLogService>> {
        self.get_service::<dyn IOperationLogService>()
    }
    /// 设置日志记录服务
    pub fn set_log_record_service(&mut self, service: impl ILogRecordService) {
        self.set_service(Arc::new(service) as Arc<dyn ILogRecordService>)
    }
    /// 获取日志记录服务
    pub fn get_log_record_service(&self) -> AppResult<Arc<dyn ILogRecordService>> {
        self.get_service::<dyn ILogRecordService>()
    }
    /// 设置字典服务
    pub fn set_dict_service(&mut self, service: impl IDictService) {
        self.set_service(Arc::new(service) as Arc<dyn IDictService>)
    }
    /// 获取字典服务
    pub fn get_dict_service(&self) -> AppResult<Arc<dyn IDictService>> {
        self.get_service::<dyn IDictService>()
    }
    /// 设置文件存储服务
    pub fn set_file_service(&mut self, service: impl IFileService) {
        self.set_service(Arc::new(service) as Arc<dyn IFileService>)
    }
    /// 获取文件存储服务
    pub fn get_file_service(&self) -> AppResult<Arc<dyn IFileService>> {
        self.get_service::<dyn IFileService>()
    }
    /// 设置日期时间服务
    pub fn set_date_time_service(&mut self, service: impl IDateTimeService) {
        self.set_service(Arc::new(service) as Arc<dyn IDateTimeService>)
    }
    /// 获取日期时间服务
    pub fn get_date_time_service(&self) -> AppResult<Arc<dyn IDateTimeService>> {
        self.get_service::<dyn IDateTimeService>()
    }
    /// 设置缓存服务
    pub fn set_cache_service<T: ICacheService>(&mut self, service: T) {
        self.set_service(Arc::new(service))
    }
    /// 获取缓存服务
    pub fn get_cache_service<T: ICacheService>(&self) -> AppResult<Arc<T>> {
        self.get_service::<T>()
    }
    /// 设置限流服务
    pub fn set_throttle_service(&mut self, service: impl IThrottleService) {
        self.set_service(Arc::new(service) as Arc<dyn IThrottleService>)
    }
    /// 获取限流服务务
    pub fn get_throttle_service(&self) -> AppResult<Arc<dyn IThrottleService>> {
        self.get_service::<dyn IThrottleService>()
    }
}

impl AppConfig {
    /// 获取配置
    pub fn get_config<T: UpdateableConfig + Send + Sync + 'static>(&self) -> AppResult<Arc<T>> {
        self.extension::<T>()
    }
    /// 设置配置
    pub fn set_config<T: UpdateableConfig + Send + Sync + 'static>(&self, config: T) {
        self.add_extension(config)
    }
    /// 获取Server配置
    pub fn get_server_config(&self) -> AppResult<Arc<ServerConfig>> {
        self.get_config::<ServerConfig>()
    }
    /// 获取注册中心配置
    pub fn get_registry_config(&self) -> AppResult<Arc<RegistryConfig>> {
        self.get_config::<RegistryConfig>()
    }
    /// 获取Security配置
    pub fn get_security_config(&self) -> AppResult<Arc<SecurityConfig>> {
        self.get_config::<SecurityConfig>()
    }
    /// 获取日志配置
    pub fn get_log_config(&self) -> AppResult<Arc<LogConfig>> {
        self.get_config::<LogConfig>()
    }
}

impl AppConfig {
    /// 获取registry client
    pub fn get_registry_client(&self) -> AppResult<Arc<RegistryClient>> {
        self.extension::<RegistryClient>()
    }
    /// 设置registry client
    fn set_registry_client(&self, client: RegistryClient) {
        self.add_extension(client)
    }
}

#[cfg(feature = "client-grpc")]
impl AppConfig {
    /// 获取gRPC client
    pub fn get_grpc_client(&self) -> AppResult<Arc<crate::tina::client::GrpcClient>> {
        self.extension::<crate::tina::client::GrpcClient>()
    }
}

#[allow(dead_code)]
fn box_fn<T, F, R>(f: F) -> impl Fn(Application) -> BoxFuture<'static, R>
where
    T: Future<Output = R> + Send + 'static,
    F: Fn(Application) -> T + Copy + Send + Sync + 'static,
    R: Send + 'static,
{
    move |application: Application| async move { f(application).await }.boxed()
}

#[allow(deprecated, dead_code)]
fn resolve_path(path: &mut String) -> AppResult<()> {
    if path.is_empty() {
        *path = Utility::get_current_exe_dir()?;
    } else if let Some(s) = path.chars().next() {
        match s {
            '.' => {
                let dir = Utility::get_current_exe_dir()?;
                *path = path.replacen(s.to_string().as_str(), dir.as_str(), 1);
            }
            '~' => match std::env::home_dir() {
                None => {
                    let dir = std::env::current_dir().map_err(app_error_from!())?;
                    *path = path.replacen(s.to_string().as_str(), dir.as_path().to_string_lossy().as_ref(), 1);
                }
                Some(dir) => {
                    *path = path.replacen(s.to_string().as_str(), dir.as_path().to_string_lossy().as_ref(), 1);
                }
            },
            _ => {}
        }
    }
    Ok(())
}

#[cfg(feature = "client-nacos")]
mod nacos {
    use crate::{
        app_system_error,
        tina::{client::registry::IRegistryClient, data::AppResult, util::not_empty::INotEmpty},
    };

    use super::Application;

    impl Application {
        /// 注册客户端
        pub fn regist_client(&self) -> AppResult<()> {
            let application = self.clone();
            std::thread::Builder::new()
                .name("注册服务线程".to_string())
                .spawn(move || {
                    let rt = tokio::runtime::Builder::new_multi_thread()
                        .worker_threads(1)
                        .enable_all()
                        .build()
                        .expect("build registry rt failed");
                    rt.block_on(async move {
                        let func = move || async move {
                            let registry_config = application.get_registry_config()?;
                            let server_addr = registry_config.address.join(",");
                            let app_name = registry_config.app_name.to_owned();
                            let mut client_builder = crate::tina::client::registry::RegistryClientBuilder::new(server_addr, app_name);
                            if let Some(v) = registry_config.username.as_ref() {
                                client_builder = client_builder.auth_username(v);
                            }
                            if let Some(v) = registry_config.password.as_ref() {
                                client_builder = client_builder.auth_password(v);
                            }
                            if let Some(v) = registry_config.namespace.as_ref() {
                                client_builder = client_builder.namespace(v);
                            }

                            let mut client = client_builder.build();
                            crate::tina::client::registry::IRegistryClient::init(&mut client, &application).await?;

                            let config_infos = registry_config.config.as_ref();
                            if let Some(config_infos) = config_infos {
                                for config_info in config_infos.iter() {
                                    let data_id = config_info.data_id.to_owned();
                                    let group = config_info.group.to_owned();
                                    if data_id.not_empty() && group.not_empty() {
                                        let config = client.get_raw_config(&application, data_id, group).await?;
                                        if let Some(config) = config {
                                            application.update_default_config(&config).await?;
                                            if let Some(func) = application.registry_config_change_fn.as_ref() {
                                                let func = func.clone();
                                                func(config).await?;
                                            }
                                        }
                                    }
                                }
                            }
                            application.set_registry_client(client);
                            tracing::info!("注册客户端成功: {:?}", application.get_registry_client()?);
                            Ok(()) as AppResult<()>
                        };
                        loop {
                            let func2 = func.clone();
                            match func2().await {
                                Ok(v) => break v,
                                Err(err) => {
                                    tracing::error!("注册客户端失败: {err:?}");
                                    tokio::time::sleep(std::time::Duration::from_secs(10)).await;
                                    continue;
                                }
                            }
                        }
                    })
                })
                .map_err(|err| app_system_error!("启动注册服务线程失败: {err:?}"))?
                .join()
                .map_err(|_| app_system_error!("启动注册服务线程失败"))?;
            Ok(())
        }
    }
}

/// 从Application转换
pub trait FromApplication {
    /// 转换后的对象
    type Target;
    /// 转换
    fn from_application(application: Application, init_components: bool) -> AppResult<Self::Target>;
}

impl Serialize for Application {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        self.0.serialize(serializer)
    }
}

/// Application扩展
#[crate::async_trait]
pub trait ApplicationExt {
    /// sleep当前任务
    async fn sleep_current_task(&self, duration: Duration);
    /// 启动一个异步任务
    fn spawn<F: Future<Output = AppResult<R>> + Send + 'static, R: Send + 'static>(&self, fut: F) -> AppResult<()>;
}