1- use std:: sync:: { Arc , Mutex } ;
1+ use std:: {
2+ collections:: VecDeque ,
3+ sync:: { Arc , Mutex } ,
4+ } ;
25use tailflow_core:: { LogReceiver , LogRecord , LogSender } ;
36use tokio:: sync:: broadcast;
47
@@ -9,7 +12,7 @@ pub struct AppState {
912 /// Subscribe to the live stream by calling `tx.subscribe()`.
1013 pub tx : LogSender ,
1114 /// Rolling buffer of the last RING_SIZE records (for `/api/records`).
12- pub ring : Mutex < Vec < LogRecord > > ,
15+ pub ring : Mutex < VecDeque < LogRecord > > ,
1316}
1417
1518impl AppState {
@@ -18,7 +21,7 @@ impl AppState {
1821 let ( tx, _) = broadcast:: channel ( tailflow_core:: BUS_CAPACITY ) ;
1922 let state = Arc :: new ( AppState {
2023 tx : tx. clone ( ) ,
21- ring : Mutex :: new ( Vec :: with_capacity ( RING_SIZE ) ) ,
24+ ring : Mutex :: new ( VecDeque :: with_capacity ( RING_SIZE ) ) ,
2225 } ) ;
2326 let state2 = state. clone ( ) ;
2427
@@ -27,11 +30,11 @@ impl AppState {
2730 match source_rx. recv ( ) . await {
2831 Ok ( record) => {
2932 {
30- let mut buf = state2. ring . lock ( ) . unwrap ( ) ;
33+ let mut buf = state2. ring . lock ( ) . unwrap_or_else ( |p| p . into_inner ( ) ) ;
3134 if buf. len ( ) >= RING_SIZE {
32- buf. remove ( 0 ) ;
35+ buf. pop_front ( ) ; // O(1) vs Vec:: remove(0) O(n)
3336 }
34- buf. push ( record. clone ( ) ) ;
37+ buf. push_back ( record. clone ( ) ) ;
3538 }
3639 let _ = tx. send ( record) ;
3740 }
0 commit comments