@@ -17,6 +17,7 @@ use super::models::TelemetryFrontendLog;
1717use crate :: config:: TelemetryConfig ;
1818use std:: sync:: atomic:: { AtomicU8 , AtomicUsize , Ordering } ;
1919use std:: sync:: { Arc , Mutex } ;
20+ use tokio:: runtime:: Handle ;
2021
2122const STATE_ACTIVE : u8 = 0 ;
2223const STATE_CLOSING : u8 = 1 ;
@@ -32,6 +33,7 @@ pub(super) struct TelemetryClient {
3233 flush_lock : tokio:: sync:: Mutex < ( ) > ,
3334 state : AtomicU8 ,
3435 timer : Mutex < Option < tokio:: task:: JoinHandle < ( ) > > > ,
36+ runtime_handle : Handle ,
3537}
3638
3739impl TelemetryClient {
@@ -50,6 +52,7 @@ impl TelemetryClient {
5052 flush_lock : tokio:: sync:: Mutex :: new ( ( ) ) ,
5153 state : AtomicU8 :: new ( STATE_ACTIVE ) ,
5254 timer : Mutex :: new ( None ) ,
55+ runtime_handle : Handle :: current ( ) ,
5356 } ) ;
5457 client. start_timer ( ) ;
5558 client
@@ -68,7 +71,7 @@ impl TelemetryClient {
6871
6972 if count >= self . batch_size {
7073 let client = Arc :: clone ( self ) ;
71- tokio :: spawn ( async move {
74+ self . runtime_handle . spawn ( async move {
7275 client. flush_once_if_idle ( ) . await ;
7376 } ) ;
7477 }
@@ -139,7 +142,7 @@ impl TelemetryClient {
139142 fn start_timer ( self : & Arc < Self > ) {
140143 let client = Arc :: downgrade ( self ) ;
141144 let interval = self . flush_interval ;
142- let handle = tokio :: spawn ( async move {
145+ let handle = self . runtime_handle . spawn ( async move {
143146 loop {
144147 tokio:: time:: sleep ( interval) . await ;
145148 let Some ( client) = client. upgrade ( ) else {
@@ -192,6 +195,39 @@ mod tests {
192195 client. close ( ) . await ;
193196 }
194197
198+ #[ tokio:: test]
199+ async fn enqueue_from_non_runtime_thread_uses_client_runtime ( ) {
200+ let exporter = CapturingTelemetryExporter :: default ( ) ;
201+ let config = TelemetryConfig {
202+ enabled : true ,
203+ batch_size : 1 ,
204+ flush_interval : Duration :: from_secs ( 60 ) ,
205+ ..TelemetryConfig :: default ( )
206+ } ;
207+ let client = TelemetryClient :: new ( & config, Arc :: new ( exporter. clone ( ) ) ) ;
208+
209+ let worker_client = Arc :: clone ( & client) ;
210+ std:: thread:: spawn ( move || {
211+ worker_client. enqueue ( sample_log ( "one" ) ) ;
212+ } )
213+ . join ( )
214+ . expect ( "enqueue from plain thread should not panic" ) ;
215+
216+ tokio:: time:: timeout ( Duration :: from_secs ( 1 ) , async {
217+ loop {
218+ if !exporter. requests ( ) . is_empty ( ) {
219+ break ;
220+ }
221+ tokio:: time:: sleep ( Duration :: from_millis ( 10 ) ) . await ;
222+ }
223+ } )
224+ . await
225+ . expect ( "batch flush should complete" ) ;
226+
227+ assert_eq ! ( exporter. requests( ) [ 0 ] . proto_logs. len( ) , 1 ) ;
228+ client. close ( ) . await ;
229+ }
230+
195231 #[ tokio:: test]
196232 async fn interval_triggers_flush_before_batch_size ( ) {
197233 let exporter = CapturingTelemetryExporter :: default ( ) ;
0 commit comments