1use futures::Future;
2use lazy_static::lazy_static;
3use tokio::runtime::Runtime;
4use xCommonLib::base::status::Status;
5use xCommonLib::protocol::protocol_dxc::ProtocolDXCReader;
6use xCommonLib::serial::request_message::RequestMessage;
7
8use protobuf::CodedInputStream;
9use tracing::{debug, info};
10use xCommonLib::base::dll_api::{
11 AddChannelIdToRemoteServicesApi, BuildChannelApi, EventResponseApi, GenIDApi, GetAllConnIdApi,
12 GetAllLocalServiceApi, GetChannelIdByConnIdApi, GetHttpDataApi, GetHttpListenAddrApi,
13 GetXPRCPortApi, HasServiceApi, LoadServiceApi, OutputLogApi, RemoveHttpClientApi,
14 RemoveRemoteServiceAllChannelIdApi, ResponseApi, SendHttpRequestApi, SendMessageApi,
15 SetChannelXRPCPortApi, SleepApi, SubscribeApi, UnLoadServiceApi, UnSubscribeApi,
16};
17
18use core::slice;
19use std::cell::RefCell;
20use std::collections::HashMap;
21use std::mem::MaybeUninit;
22use std::sync::{Arc, Mutex};
23use std::task::{Context, Poll, Waker};
24
25pub static mut RUNTIME: MaybeUninit<Runtime> = MaybeUninit::uninit();
26
27pub static mut SEND_MESSAGE_API: MaybeUninit<SendMessageApi> = MaybeUninit::uninit();
28
29pub static mut HAS_SERVICE_API: MaybeUninit<HasServiceApi> = MaybeUninit::uninit();
30
31pub(crate) static mut SLEEP_API: MaybeUninit<SleepApi> = MaybeUninit::uninit();
32
33pub(crate) static mut GEN_ID_API: MaybeUninit<GenIDApi> = MaybeUninit::uninit();
34pub(crate) static mut RESPONSE_FUNC_API: MaybeUninit<ResponseApi> = MaybeUninit::uninit();
35
36pub(crate) static mut EVENT_RESPONSE_FUNC_API: MaybeUninit<EventResponseApi> =
37 MaybeUninit::uninit();
38
39pub(crate) static mut OUTPUT_LOG_API: MaybeUninit<OutputLogApi> = MaybeUninit::uninit();
40pub(crate) static mut LOAD_SERVICE_API: MaybeUninit<LoadServiceApi> = MaybeUninit::uninit();
41pub(crate) static mut UNLOAD_SERVICE_API: MaybeUninit<UnLoadServiceApi> = MaybeUninit::uninit();
42
43pub(crate) static mut SEND_HTTP_REQUEST_API: MaybeUninit<SendHttpRequestApi> =
45 MaybeUninit::uninit();
46pub(crate) static mut GET_HTTP_DATA_API: MaybeUninit<GetHttpDataApi> = MaybeUninit::uninit();
47pub(crate) static mut REMOVE_HTTP_CLIENT_API: MaybeUninit<RemoveHttpClientApi> =
48 MaybeUninit::uninit();
49
50pub(crate) static mut GET_HTTP_LISTEN_ADDR_API: MaybeUninit<GetHttpListenAddrApi> =
51 MaybeUninit::uninit();
52pub(crate) static mut BUILD_CHANNEL_API: MaybeUninit<BuildChannelApi> = MaybeUninit::uninit();
54
55pub(crate) static mut GET_ALL_LOCAL_SERVICE: MaybeUninit<GetAllLocalServiceApi> =
56 MaybeUninit::uninit();
57
58pub(crate) static mut ADD_CHANNEL_ID_TO_REMOTE_SERVICE: MaybeUninit<
59 AddChannelIdToRemoteServicesApi,
60> = MaybeUninit::uninit();
61
62pub(crate) static mut REMOVE_REMOTE_SERVICE_ALL_CHANNEL_ID: MaybeUninit<
63 RemoveRemoteServiceAllChannelIdApi,
64> = MaybeUninit::uninit();
65
66pub(crate) static mut SET_CHANNEL_XRPC_PORT: MaybeUninit<SetChannelXRPCPortApi> =
67 MaybeUninit::uninit();
68
69pub(crate) static mut GET_XRPC_PORT: MaybeUninit<GetXPRCPortApi> = MaybeUninit::uninit();
70
71pub(crate) static mut GET_ALL_CONN_ID: MaybeUninit<GetAllConnIdApi> = MaybeUninit::uninit();
72
73pub(crate) static mut GET_CHANNEL_ID_BY_CONN_ID: MaybeUninit<GetChannelIdByConnIdApi> =
74 MaybeUninit::uninit();
75
76pub(crate) static mut SUBSCRIBE: MaybeUninit<SubscribeApi> = MaybeUninit::uninit();
77
78pub(crate) static mut UNSUBSCRIBE: MaybeUninit<UnSubscribeApi> = MaybeUninit::uninit();
79
80pub(crate) static mut SERVICE_ID: i64 = 0;
81
82thread_local! {
83 pub static CUR_REQUEST_ID:RefCell<i64> = RefCell::new(0);
84}
85
86pub fn set_request_id(request_id: i64) {
87 CUR_REQUEST_ID.with(move |id| {
88 *id.borrow_mut() = request_id;
89 });
90}
91
92pub fn get_request_id() -> i64 {
93 CUR_REQUEST_ID.with(move |id| *id.borrow())
94}
95
96#[no_mangle]
97pub extern "C" fn inject_send_message(api: SendMessageApi) {
98 unsafe {
99 SEND_MESSAGE_API.as_mut_ptr().write(api);
100 }
101}
102
103#[no_mangle]
104pub extern "C" fn inject_has_service(api: HasServiceApi) {
105 unsafe {
106 HAS_SERVICE_API.as_mut_ptr().write(api);
107 }
108}
109
110#[no_mangle]
111pub extern "C" fn inject_sleep(api: SleepApi) {
112 unsafe {
113 SLEEP_API.as_mut_ptr().write(api);
114 }
115}
116
117#[no_mangle]
118pub extern "C" fn inject_response_func(api: ResponseApi) {
119 unsafe {
120 RESPONSE_FUNC_API.as_mut_ptr().write(api);
121 }
122}
123
124#[no_mangle]
125pub extern "C" fn inject_event_response_func(api: EventResponseApi) {
126 unsafe {
127 EVENT_RESPONSE_FUNC_API.as_mut_ptr().write(api);
128 }
129}
130
131#[no_mangle]
134pub extern "C" fn inject_gen_id(api: GenIDApi) {
135 unsafe {
136 GEN_ID_API.as_mut_ptr().write(api);
137 }
138}
139
140#[no_mangle]
141pub extern "C" fn inject_build_channel(api: BuildChannelApi) {
142 unsafe {
143 BUILD_CHANNEL_API.as_mut_ptr().write(api);
144 }
145}
146
147#[no_mangle]
148pub extern "C" fn inject_get_all_local_service(api: GetAllLocalServiceApi) {
149 unsafe {
150 GET_ALL_LOCAL_SERVICE.as_mut_ptr().write(api);
151 }
152}
153
154#[no_mangle]
155pub extern "C" fn inject_add_channel_id_to_remote_services(api: AddChannelIdToRemoteServicesApi) {
156 unsafe {
157 ADD_CHANNEL_ID_TO_REMOTE_SERVICE.as_mut_ptr().write(api);
158 }
159}
160
161#[no_mangle]
162pub extern "C" fn inject_remove_remote_services_all_channel_id(
163 api: RemoveRemoteServiceAllChannelIdApi,
164) {
165 unsafe {
166 REMOVE_REMOTE_SERVICE_ALL_CHANNEL_ID.as_mut_ptr().write(api);
167 }
168}
169
170#[no_mangle]
171pub extern "C" fn inject_set_channel_xrpc_port(api: SetChannelXRPCPortApi) {
172 unsafe {
173 SET_CHANNEL_XRPC_PORT.as_mut_ptr().write(api);
174 }
175}
176#[no_mangle]
178pub extern "C" fn inject_get_xrpc_port(api: GetXPRCPortApi) {
179 unsafe {
180 GET_XRPC_PORT.as_mut_ptr().write(api);
181 }
182}
183
184#[no_mangle]
185pub extern "C" fn result_in(request_id: i64, buffer: *const u8, buffer_len: u32) {
186 debug!("result_in 消息 = {}", request_id);
188 let handler = {
189 let mut handler_map = REQUEST_ID_MAP.lock().unwrap();
190 handler_map.remove(&request_id)
191 };
192 if handler.is_none() {
193 debug!("返回消息: ={},无处理....", request_id);
194 return;
195 }
196 let vec_buffer = unsafe { slice::from_raw_parts(buffer as *mut u8, buffer_len as usize) };
197
198 let reader = ProtocolDXCReader::new(&vec_buffer);
199
200 let msg_body = reader.msg_body();
201
202 handler.unwrap()(msg_body);
203
204}
205
206#[no_mangle]
207pub extern "C" fn inject_log_output(api: OutputLogApi) {
208 unsafe {
209 OUTPUT_LOG_API.as_mut_ptr().write(api);
210 }
211}
212
213#[no_mangle]
215pub extern "C" fn inject_load_service(api: LoadServiceApi) {
216 unsafe {
217 LOAD_SERVICE_API.as_mut_ptr().write(api);
218 }
219}
220#[no_mangle]
222pub extern "C" fn inject_unload_service(api: UnLoadServiceApi) {
223 unsafe {
224 UNLOAD_SERVICE_API.as_mut_ptr().write(api);
225 }
226}
227
228#[no_mangle]
230pub extern "C" fn inject_send_http_request(api: SendHttpRequestApi) {
231 unsafe {
232 SEND_HTTP_REQUEST_API.as_mut_ptr().write(api);
233 }
234}
235#[no_mangle]
237pub extern "C" fn inject_get_http_listen_addr(api: GetHttpListenAddrApi) {
238 unsafe {
239 GET_HTTP_LISTEN_ADDR_API.as_mut_ptr().write(api);
240 }
241}
242#[no_mangle]
244pub extern "C" fn inject_get_http_data(api: GetHttpDataApi) {
245 unsafe {
246 GET_HTTP_DATA_API.as_mut_ptr().write(api);
247 }
248}
249
250#[no_mangle]
252pub extern "C" fn inject_remove_http_client(api: RemoveHttpClientApi) {
253 unsafe {
254 REMOVE_HTTP_CLIENT_API.as_mut_ptr().write(api);
255 }
256}
257
258#[no_mangle]
260pub extern "C" fn inject_get_all_conn_id(api: GetAllConnIdApi) {
261 unsafe {
262 GET_ALL_CONN_ID.as_mut_ptr().write(api);
263 }
264}
265
266#[no_mangle]
268pub extern "C" fn inject_get_channel_id_by_conn_id(api: GetChannelIdByConnIdApi) {
269 unsafe {
270 GET_CHANNEL_ID_BY_CONN_ID.as_mut_ptr().write(api);
271 }
272}
273
274#[no_mangle]
275pub extern "C" fn inject_subscribe(api: SubscribeApi) {
276 unsafe {
277 SUBSCRIBE.as_mut_ptr().write(api);
278 }
279}
280#[no_mangle]
281pub extern "C" fn inject_unsubscribe(api: UnSubscribeApi) {
282 unsafe {
283 UNSUBSCRIBE.as_mut_ptr().write(api);
284 }
285}
286pub type Result<T> = std::result::Result<T, Status>;
290
291pub mod xrpc {
292 use xCommonLib::service::sys_service_api::ServiceKey;
293
294 pub struct Context {
295 pub sender_service_key: ServiceKey,
296 pub channel_id: i64,
297 pub request_id: i64,
298 pub from_addr:String,
299 }
300}
301
302pub fn gen_id() -> i64 {
303 unsafe { GEN_ID_API.assume_init_ref()(get_service_id()) }
304}
305
306pub fn get_service_id() -> i64 {
307 unsafe { SERVICE_ID }
308}
309
310lazy_static! {
311 static ref REQUEST_ID_MAP: Mutex<HashMap<i64, Box<dyn Fn(&[u8]) + Send + Sync>>> =
312 Mutex::new(HashMap::new());
313}
314
315pub struct RequestState<T> {
316 pub is_finish: bool,
317 pub status: Status,
318 pub value: Option<T>,
319 pub waker: Option<Waker>,
320}
321
322pub fn create_request_state<T>() -> Arc<Mutex<RequestState<T>>> {
323 Arc::new(Mutex::new(RequestState {
324 is_finish: false,
325 status: Status::default(),
326 value: None,
327 waker: None,
328 }))
329}
330
331pub struct RequestFuture<T> {
332 pub shared_state: Arc<Mutex<RequestState<T>>>,
333}
334
335impl<T> Future for RequestFuture<T> {
336 type Output = Result<T>;
337 fn poll(self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
338 let mut shared_state = self.shared_state.lock().unwrap();
339 if shared_state.is_finish {
340 if shared_state.status.err_code != 0 {
341 let err_msg = std::mem::take(&mut shared_state.status.err_msg);
342 return Poll::Ready(Err(Status::new(1, err_msg)));
343 } else {
344 let value = shared_state.value.take();
345
346 return Poll::Ready(Ok(value.unwrap()));
347 }
348 }
349 shared_state.waker = Some(cx.waker().clone());
350 Poll::Pending
351 }
352}
353
354pub struct RequestEmptyFuture {
355 pub shared_state: Arc<Mutex<RequestState<()>>>,
356}
357
358impl Future for RequestEmptyFuture {
359 type Output = Result<()>;
360 fn poll(self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
361 let mut shared_state = self.shared_state.lock().unwrap();
362 if shared_state.is_finish {
363 if shared_state.status.err_code != 0 {
364 let err_msg = std::mem::take(&mut shared_state.status.err_msg);
365 return Poll::Ready(Err(Status::new(1, err_msg)));
366 } else {
367 return Poll::Ready(Ok(()));
368 }
369 }
370 shared_state.waker = Some(cx.waker().clone());
371 Poll::Pending
372 }
373}
374
375pub fn build_request_future<T>() -> (RequestFuture<T>, i64, bool) {
379 let request_id = gen_id();
380 let future = RequestFuture {
381 shared_state: create_request_state(),
382 };
383
384 return (future, request_id, true);
385}
386
387pub fn build_request_empty_future() -> (RequestEmptyFuture, i64, bool) {
388 let request_id = gen_id();
389 let future = RequestEmptyFuture {
390 shared_state: create_request_state(),
391 };
392
393 return (future, request_id, true);
394}
395
396pub fn serial_empty_request(message: &str) -> Vec<u8> {
397 let size = protobuf::rt::string_size(1, message);
398
399 let mut buffer: Vec<u8> = Vec::with_capacity(size as usize);
400
401 let mut os = protobuf::CodedOutputStream::vec(&mut buffer);
402
403 os.write_string(1, message).unwrap();
404
405 os.flush().unwrap();
406
407 drop(os);
408
409 buffer
410}
411
412pub fn serial_request<T>(message: &str, param: &T) -> Vec<u8>
414where
415 T: RequestMessage,
416{
417 let mut size = protobuf::rt::string_size(1, message);
418
419 size += param.compute_size();
420
421 let mut buffer: Vec<u8> = Vec::with_capacity(size as usize);
422
423 let mut os = protobuf::CodedOutputStream::vec(&mut buffer);
424
425 os.write_string(1, message).unwrap();
426
427 param.serial_with_output_stream(&mut os).unwrap();
428
429 os.flush().unwrap();
430
431 drop(os);
432
433 buffer
434}
435
436pub fn parse_request_param<T>(is: &mut protobuf::CodedInputStream<'_>) -> T
437where
438 T: RequestMessage + Default,
439{
440 let mut param = T::default();
441
442 if is.check_eof().is_ok() {
443 return param;
444 }
445 param.parse_from_input_stream(is).unwrap();
446 param
447}
448
449pub fn parse_empty_response_and_wake(shared_state: &Arc<Mutex<RequestState<()>>>, buffer: &[u8]) {
450 let waker = {
451 let mut shared_state = shared_state.lock().unwrap();
452 let waker = shared_state.waker.take();
454 if waker.is_none() {
455 return;
456 }
457
458 let mut is = CodedInputStream::from_bytes(buffer);
459
460 is.read_raw_tag_or_eof().unwrap();
461 let _rsp_message = is.read_string().unwrap();
462
463 shared_state
464 .status
465 .parse_from_input_stream_with_tag_and_len(&mut is);
466 shared_state.is_finish = true;
467 waker
468 };
469 waker.unwrap().wake_by_ref();
470}
471
472pub fn parse_response_and_wake<T>(shared_state: &Arc<Mutex<RequestState<T>>>, buffer: &[u8])
473where
474 T: RequestMessage + Default,
475{
476 let waker = {
477 let mut shared_state = shared_state.lock().unwrap();
478 let waker = shared_state.waker.take();
480 if waker.is_none() {
481 return;
482 }
483
484 let mut is = CodedInputStream::from_bytes(buffer);
485
486 is.read_raw_tag_or_eof().unwrap();
487 let _rsp_message = is.read_string().unwrap();
488 shared_state
489 .status
490 .parse_from_input_stream_with_tag_and_len(&mut is);
491
492 if is.pos() != buffer.len() as u64 {
493 let mut value = T::default();
494
495 value.parse_from_input_stream_with_tag_and_len(&mut is);
496
497 shared_state.value = Some(value);
498 }
499 shared_state.is_finish = true;
500 waker
501 };
502
503 waker.unwrap().wake_by_ref();
504}
505
506pub fn add_request_handler(request_id: i64, handler: Box<dyn Fn(&[u8]) + Send + Sync>) {
507 let mut handler_map = REQUEST_ID_MAP.lock().unwrap();
508 handler_map.insert(request_id, handler);
509}
510
511pub struct Task<F>
512where
513 F: Future + Send + 'static,
514{
515 request_id: i64,
516 future: F,
517}
518
519impl<F> Future for Task<F>
520where
521 F: Future + Send + 'static,
522{
523 type Output = F::Output;
524 fn poll(mut self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
525 set_request_id(self.request_id);
526 let future = unsafe { self.as_mut().map_unchecked_mut(|t| &mut t.future) };
528 let ret = future.poll(cx);
529 set_request_id(0);
530 ret
531 }
532}
533
534pub fn spawn(future: impl Future<Output = ()> + 'static + Send) {
535 let request_id = get_request_id();
536 let task = Task {
537 request_id,
538 future: future,
539 };
540
541 let runtime = get_runtime();
542
543 runtime.spawn(task);
544}
545
546fn serial_only_status(rsp_message: &str, status: &Status) -> Vec<u8> {
547 let mut size = protobuf::rt::string_size(1, rsp_message);
548 let status_size = status.compute_size_with_tag_and_len();
549 size += status_size;
550 let mut buffer: Vec<u8> = Vec::with_capacity(size as usize);
551 let mut os = protobuf::CodedOutputStream::vec(&mut buffer);
552 os.write_string(1, rsp_message).unwrap();
553 status.serial_with_tag_and_len(&mut os);
554 drop(os);
555 buffer
556}
557
558pub fn response_empty_msg(rsp_message: &str, request_id: i64, result: &Result<()>) {
559 let buffer = match result {
560 Ok(_) => {
561 let status = xCommonLib::base::status::Status::default();
563 serial_only_status(rsp_message, &status)
564 }
565 Err(err) => serial_only_status(rsp_message, err),
566 };
567
568 unsafe {
569 RESPONSE_FUNC_API.assume_init_ref()(
570 get_service_id(),
571 request_id,
572 buffer.as_ptr(),
573 buffer.len() as u32,
574 );
575 }
576}
577
578pub fn response_msg<T>(rsp_message: &str, request_id: i64, result: &Result<T>)
579where
580 T: RequestMessage,
581{
582 let buffer = match result {
583 Ok(val) => {
584 let mut size = protobuf::rt::string_size(1, rsp_message);
587 let status = xCommonLib::base::status::Status::default();
588 size += status.compute_size_with_tag_and_len();
589 size += val.compute_size_with_tag_and_len();
590
591 let mut buffer: Vec<u8> = Vec::with_capacity(size as usize);
592
593 let mut os = protobuf::CodedOutputStream::vec(&mut buffer);
594
595 os.write_string(1, rsp_message).unwrap();
596 status.serial_with_tag_and_len(&mut os);
597 val.serial_with_tag_and_len(&mut os);
598
599 drop(os);
600 buffer
601 }
602 Err(err) => serial_only_status(rsp_message, err),
603 };
604
605 unsafe {
606 RESPONSE_FUNC_API.assume_init_ref()(
607 get_service_id(),
608 request_id,
609 buffer.as_ptr(),
610 buffer.len() as u32,
611 );
612 }
613}
614
615pub mod config {
616 use toml::Table;
617
618 pub(crate) static mut CONFIG_TABLE: Option<Table> = None;
619
620 pub(super) fn init(config: &str) {
621 let table: Table = toml::from_str(config).expect("解析配置文件失败!");
622
623 unsafe {
624 CONFIG_TABLE = Some(table);
625 }
626 }
627
628 pub fn get_str(key: &str) -> Option<&str> {
632 unsafe {
633 if let Some(table) = CONFIG_TABLE.as_ref() {
634 let value = table.get(key);
635 if value.is_none() {
636 return None;
637 }
638 return value.unwrap().as_str();
639 }
640 None
641 }
642 }
643 pub fn get_str_array(key: &str) -> Vec<Option<&str>> {
647 unsafe {
648 if let Some(table) = CONFIG_TABLE.as_ref() {
649 let value = table.get(key);
650 if value.is_none() {
651 return Vec::new();
652 }
653 let value = value.unwrap();
654 if value.is_array() {
655 let mut vec = Vec::new();
656 let value = value.as_array().unwrap();
657 for ele in value {
658 vec.push(ele.as_str())
659 }
660 }
661 return vec![value.as_str()];
662 }
663 Vec::new()
664 }
665 }
666 pub fn get_i32(key: &str) -> Option<i32> {
668 unsafe {
669 if let Some(table) = CONFIG_TABLE.as_ref() {
670 let value = table.get(key);
671 if value.is_none() {
672 return None;
673 }
674 let value = value.unwrap();
675 return if value.is_integer() {
676 Some(value.as_integer().unwrap() as i32)
677 } else {
678 let str_val = value.as_str().unwrap();
679 let i32_val = str_val.parse::<i32>();
680 match i32_val {
681 Ok(val) => Some(val),
682 Err(_) => None,
683 }
684 };
685 }
686 None
687 }
688 }
689 pub fn get_i64(key: &str) -> Option<i64> {
691 unsafe {
692 if let Some(table) = CONFIG_TABLE.as_ref() {
693 let value = table.get(key);
694 if value.is_none() {
695 return None;
696 }
697 let value = value.unwrap();
698 return if value.is_integer() {
699 Some(value.as_integer().unwrap() as i64)
700 } else {
701 let str_val = value.as_str().unwrap();
702 let i32_val = str_val.parse::<i64>();
703 match i32_val {
704 Ok(val) => Some(val),
705 Err(_) => None,
706 }
707 };
708 }
709 None
710 }
711 }
712 pub fn get_f32(key: &str) -> Option<f32> {
714 unsafe {
715 if let Some(table) = CONFIG_TABLE.as_ref() {
716 let value = table.get(key);
717 if value.is_none() {
718 return None;
719 }
720 let value = value.unwrap();
721 return if value.is_integer() {
722 Some(value.as_integer().unwrap() as f32)
723 } else {
724 let str_val = value.as_str().unwrap();
725 let i32_val = str_val.parse::<f32>();
726 match i32_val {
727 Ok(val) => Some(val),
728 Err(_) => None,
729 }
730 };
731 }
732 None
733 }
734 }
735 pub fn get_f64(key: &str) -> Option<f64> {
737 unsafe {
738 if let Some(table) = CONFIG_TABLE.as_ref() {
739 let value = table.get(key);
740 if value.is_none() {
741 return None;
742 }
743 let value = value.unwrap();
744 return if value.is_integer() {
745 Some(value.as_integer().unwrap() as f64)
746 } else {
747 let str_val = value.as_str().unwrap();
748 let i32_val = str_val.parse::<f64>();
749 match i32_val {
750 Ok(val) => Some(val),
751 Err(_) => None,
752 }
753 };
754 }
755 None
756 }
757 }
758 pub fn get_bool(key: &str) -> Option<bool> {
760 unsafe {
761 if let Some(table) = CONFIG_TABLE.as_ref() {
762 let value = table.get(key);
763 if value.is_none() {
764 return None;
765 }
766 return value.unwrap().as_bool();
767 }
768 None
769 }
770 }
771}
772
773mod logger {
775 use super::OUTPUT_LOG_API;
776 use std::fmt::Debug;
777 use std::io::Write;
778 use tracing::field::{Field, Visit};
779 use tracing::span::{self, Attributes, Record};
780 use tracing::{Event, Id, Level, Metadata, Subscriber};
781 use xCommonLib::utils::time_utils;
782
783 struct FieldVisitor {
784 buffer: Vec<u8>,
785 }
786
787 pub(super) struct LoggerSubscriber {
788 pub(super) level: Level,
789 pub(super) service: String,
790 }
791
792 fn output_log(log_buffer: &Vec<u8>) {
794 unsafe {
795 OUTPUT_LOG_API.assume_init_ref()(
796 super::get_service_id(),
797 log_buffer.as_ptr(),
798 log_buffer.len() as u32,
799 );
800 }
801 }
802
803 pub(crate) fn init(service: &str, log_level: i32) {
804 let level = match log_level {
805 0 => Level::TRACE,
806 1 => Level::DEBUG,
807 2 => Level::INFO,
808 3 => Level::WARN,
809 4 => Level::ERROR,
810 _ => Level::INFO,
811 };
812
813 let subscriber = LoggerSubscriber {
814 service: service.to_string(),
815 level: level,
816 };
817 tracing::subscriber::set_global_default(subscriber).expect("初始化日志库失败!");
819 }
820
821 impl Visit for FieldVisitor {
822 fn record_debug(&mut self, field: &Field, value: &dyn Debug) {
823 if field.name() == "message" {
824 write!(&mut self.buffer, "{:?}", value).expect("打印日志失败!");
825 }
826 }
827 }
828
829 impl LoggerSubscriber {
830 const TRACE_STR: &str = "TRACE";
831 const DEBUG_STR: &str = "DEBUG";
832 const INFO_STR: &str = " INFO";
833 const WARN_STR: &str = " WARN";
834 const ERROR_STR: &str = "ERROR";
835
836 fn level_fmt(level: Level) -> &'static str {
837 match level {
838 Level::TRACE => Self::TRACE_STR,
839 Level::DEBUG => Self::DEBUG_STR,
840 Level::INFO => Self::INFO_STR,
841 Level::WARN => Self::WARN_STR,
842 Level::ERROR => Self::ERROR_STR,
843 }
844 }
845 }
846
847 impl Subscriber for LoggerSubscriber {
848 fn enabled(&self, metadata: &Metadata<'_>) -> bool {
849 *metadata.level() <= self.level
850 }
851 fn new_span(&self, _span: &Attributes<'_>) -> Id {
852 span::Id::from_u64(super::gen_id() as u64)
853 }
854 fn record(&self, _span: &Id, _values: &Record<'_>) {}
855
856 fn record_follows_from(&self, _span: &Id, _follows: &Id) {}
857
858 fn event(&self, event: &Event<'_>) {
859 let mut visitor = FieldVisitor { buffer: Vec::new() };
860 write!(
861 &mut visitor.buffer,
862 "{} {} {} {} {}: ",
863 time_utils::cur_time_str(),
864 Self::level_fmt(*event.metadata().level()),
865 self.service,
866 event.metadata().file().unwrap(),
867 event.metadata().line().unwrap()
868 )
869 .expect("打印日志失败!");
870
871 event.record(&mut visitor);
873 write!(&mut visitor.buffer, "\n").expect("打印日志失败!");
874
875 output_log(&visitor.buffer);
876 }
878 fn enter(&self, _span: &Id) {}
879 fn exit(&self, _span: &Id) {}
880 }
881}
882
883pub fn init_runtime() {
888 let runtime = tokio::runtime::Builder::new_multi_thread()
889 .worker_threads(4) .enable_all()
891 .build()
892 .unwrap();
893 unsafe {
894 RUNTIME.as_mut_ptr().write(runtime);
895 }
896}
897
898pub fn get_runtime() -> &'static Runtime {
899 unsafe { RUNTIME.assume_init_ref() }
900}
901
902pub fn init_app(service_id: i64, service: &str, config: &str, log_level: i32) {
906 unsafe {
907 SERVICE_ID = service_id;
908 }
909 config::init(config);
911 logger::init(service, log_level);
913}