11use crate :: prelude:: * ;
22
3- use std:: collections:: BTreeMap ;
4- use std:: sync:: { Arc , RwLock } ;
5-
63use crate :: execution:: source_indexer:: SourceIndexingContext ;
74use crate :: service:: error:: ApiError ;
85use crate :: settings;
96use crate :: setup;
107use crate :: { builder:: AnalyzedFlow , execution:: query:: SimpleSemanticsQueryHandler } ;
118use axum:: http:: StatusCode ;
129use sqlx:: PgPool ;
10+ use std:: collections:: BTreeMap ;
1311use tokio:: runtime:: Runtime ;
1412
1513pub struct FlowContext {
@@ -60,8 +58,9 @@ impl FlowContext {
6058 }
6159}
6260
61+ static TOKIO_RUNTIME : LazyLock < Runtime > = LazyLock :: new ( || Runtime :: new ( ) . unwrap ( ) ) ;
62+
6363pub struct LibContext {
64- pub runtime : Runtime ,
6564 pub pool : PgPool ,
6665 pub flows : Mutex < BTreeMap < String , Arc < FlowContext > > > ,
6766 pub combined_setup_states : RwLock < setup:: AllSetupState < setup:: ExistingMode > > ,
@@ -83,20 +82,47 @@ impl LibContext {
8382 }
8483}
8584
85+ pub fn get_runtime ( ) -> & ' static Runtime {
86+ & TOKIO_RUNTIME
87+ }
88+
89+ static LIB_INIT : OnceLock < ( ) > = OnceLock :: new ( ) ;
8690pub fn create_lib_context ( settings : settings:: Settings ) -> Result < LibContext > {
87- console_subscriber:: init ( ) ;
88- env_logger:: init ( ) ;
91+ LIB_INIT . get_or_init ( || {
92+ console_subscriber:: init ( ) ;
93+ env_logger:: init ( ) ;
94+ pyo3_async_runtimes:: tokio:: init_with_runtime ( get_runtime ( ) ) . unwrap ( ) ;
95+ } ) ;
8996
90- let runtime = Runtime :: new ( ) ?;
91- let ( pool, all_css) = runtime. block_on ( async {
97+ let ( pool, all_css) = get_runtime ( ) . block_on ( async {
9298 let pool = PgPool :: connect ( & settings. database_url ) . await ?;
9399 let existing_ss = setup:: get_existing_setup_state ( & pool) . await ?;
94100 anyhow:: Ok ( ( pool, existing_ss) )
95101 } ) ?;
96102 Ok ( LibContext {
97- runtime,
98103 pool,
99104 combined_setup_states : RwLock :: new ( all_css) ,
100105 flows : Mutex :: new ( BTreeMap :: new ( ) ) ,
101106 } )
102107}
108+
109+ static LIB_CONTEXT : RwLock < Option < Arc < LibContext > > > = RwLock :: new ( None ) ;
110+
111+ pub ( crate ) fn init_lib_context ( settings : settings:: Settings ) -> Result < ( ) > {
112+ let mut lib_context_locked = LIB_CONTEXT . write ( ) . unwrap ( ) ;
113+ * lib_context_locked = Some ( Arc :: new ( create_lib_context ( settings) ?) ) ;
114+ Ok ( ( ) )
115+ }
116+
117+ pub ( crate ) fn get_lib_context ( ) -> Result < Arc < LibContext > > {
118+ let lib_context_locked = LIB_CONTEXT . read ( ) . unwrap ( ) ;
119+ lib_context_locked
120+ . as_ref ( )
121+ . cloned ( )
122+ . ok_or_else ( || anyhow ! ( "CocoIndex library is not initialized or already stopped" ) )
123+ }
124+
125+ pub ( crate ) fn clear_lib_context ( ) {
126+ let mut lib_context_locked = LIB_CONTEXT . write ( ) . unwrap ( ) ;
127+ * lib_context_locked = None ;
128+ }
0 commit comments