@@ -147,9 +147,14 @@ pub struct AggregateLsn {
147147 /// `active_connections` means a client is connected but stalled before
148148 /// `START_REPLICATION`, which reads as "nothing attached" otherwise.
149149 pub accepted_total : u64 ,
150- /// Monotonic count of connections dropped by `slow_threshold`
151- /// overflow since process start.
152- pub dropped_total : u64 ,
150+ /// Monotonic count of sockets that ended, indexed by [`Disconnect`]
151+ pub disconnects_total : [ u64 ; Disconnect :: COUNT ] ,
152+ /// Monotonic count of `START_REPLICATION` bytes replayed from the retained
153+ /// wire buffer to reconnecting clients
154+ pub backfill_bytes_total : u64 ,
155+ /// Largest unsent send queue across connections, to read against
156+ /// `slow_threshold`
157+ pub send_queue_bytes : u64 ,
153158 /// Oldest branch an attached client is still reading: a historic
154159 /// connection is pinned to the branch its `ends_at` names, the rest to the
155160 /// served one. `None` with nothing attached. Beside the apply LSN it is
@@ -186,6 +191,23 @@ impl Refused {
186191 }
187192}
188193
194+ /// Why a walsender socket ended; the `reason=` label of
195+ /// `walshadow_shadow_stream_disconnects_total`
196+ #[ derive( Debug , Clone , Copy , PartialEq , Eq ) ]
197+ pub enum Disconnect {
198+ /// Dropped for overflowing `slow_threshold`
199+ SlowClient ,
200+ /// Client hung up cleanly
201+ ClientClosed ,
202+ /// Handshake, I/O, protocol failure, or a refused `START_REPLICATION`
203+ Error ,
204+ }
205+
206+ impl Disconnect {
207+ pub const COUNT : usize = 3 ;
208+ pub const LABELS : [ & ' static str ; Self :: COUNT ] = [ "slow_client" , "client_closed" , "error" ] ;
209+ }
210+
189211#[ derive( Debug , Error ) ]
190212pub enum ShadowStreamError {
191213 #[ error( "io: {0}" ) ]
@@ -219,10 +241,9 @@ pub struct ShadowStreamState {
219241 pub slow_threshold : usize ,
220242 /// Populates `'w'`/`'k'` frame headers.
221243 pub server_wal_end : Pos < SourceReceived > ,
222- /// Surfaced via [`AggregateLsn::dropped_total`] for the
223- /// `walshadow_shadow_stream_dropped_connections_total` gauge.
224- dropped_total : u64 ,
225244 accepted_total : u64 ,
245+ disconnects_total : [ u64 ; Disconnect :: COUNT ] ,
246+ backfill_bytes_total : u64 ,
226247 /// Wire bytes `[wire_buf_start, server_wal_end]` not yet on disk, used to
227248 /// backfill a reconnect behind the live head (else it gets an unappliable
228249 /// gap and strands at segment boundaries). Spans up to two segments while
@@ -257,8 +278,9 @@ impl ShadowStreamState {
257278 send_queues : HashMap :: new ( ) ,
258279 slow_threshold,
259280 server_wal_end : Pos :: new ( current_lsn) ,
260- dropped_total : 0 ,
261281 accepted_total : 0 ,
282+ disconnects_total : [ 0 ; Disconnect :: COUNT ] ,
283+ backfill_bytes_total : 0 ,
262284 wire_buf : Vec :: new ( ) ,
263285 wire_buf_start : current_lsn,
264286 queued : Monotone :: default ( ) ,
@@ -304,7 +326,9 @@ impl ShadowStreamState {
304326 min_apply_lsn : ( active > 0 ) . then_some ( min_apply) ,
305327 active_connections : active,
306328 accepted_total : self . accepted_total ,
307- dropped_total : self . dropped_total ,
329+ disconnects_total : self . disconnects_total ,
330+ backfill_bytes_total : self . backfill_bytes_total ,
331+ send_queue_bytes : self . send_queues . values ( ) . map ( Vec :: len) . max ( ) . unwrap_or ( 0 ) as u64 ,
308332 replay_timeline : ( active > 0 ) . then_some ( branch) ,
309333 }
310334 }
@@ -317,6 +341,11 @@ impl ShadowStreamState {
317341 self . accepted_total += 1 ;
318342 }
319343
344+ /// Count a socket ending, once per socket.
345+ pub fn note_disconnect ( & mut self , reason : Disconnect ) {
346+ self . disconnects_total [ reason as usize ] += 1 ;
347+ }
348+
320349 /// Refuse a `START_REPLICATION` this walsender cannot serve gap-free
321350 ///
322351 /// `ends_at` comes from the handshake, which resolved the request against
@@ -332,6 +361,12 @@ impl ShadowStreamState {
332361 return Err ( Refused :: Timeline ( timeline) ) ;
333362 }
334363 if start_lsn < self . wire_buf_start {
364+ tracing:: warn!(
365+ target: "walshadow::shadow_stream" ,
366+ start_lsn = %format_pg_lsn( start_lsn) ,
367+ retained_from = %format_pg_lsn( self . wire_buf_start) ,
368+ "START_REPLICATION below the retained wire buffer; the walreceiver takes that range from restore_command" ,
369+ ) ;
335370 return Err ( Refused :: Archived {
336371 start : start_lsn,
337372 retained : self . wire_buf_start ,
@@ -551,6 +586,7 @@ impl ShadowStreamState {
551586 if let Some ( c) = self . connections . get_mut ( & id) {
552587 c. backfill_queued = self . send_queues . get ( & id) . map_or ( 0 , Vec :: len) ;
553588 }
589+ self . backfill_bytes_total += backfill. len ( ) as u64 ;
554590 self . advance_dispatched ( id, Pos :: new ( server_wal_end) ) ;
555591 }
556592
@@ -615,10 +651,8 @@ impl ShadowStreamState {
615651 pub fn enqueue ( & mut self , id : u64 , framed : Vec < u8 > ) -> bool {
616652 let q = self . send_queues . entry ( id) . or_default ( ) ;
617653 if q. len ( ) + framed. len ( ) > self . slow_threshold {
618- if let Some ( c) = self . connections . get_mut ( & id)
619- && c. phase . close ( )
620- {
621- self . dropped_total += 1 ;
654+ if let Some ( c) = self . connections . get_mut ( & id) {
655+ c. phase . close ( ) ;
622656 }
623657 self . send_queues . remove ( & id) ;
624658 return false ;
@@ -650,10 +684,8 @@ impl ShadowStreamState {
650684 && envelope_start. saturating_sub ( backfill) + 1 + payload_len > cap
651685 {
652686 q. truncate ( envelope_start) ;
653- if let Some ( c) = self . connections . get_mut ( & id)
654- && c. phase . close ( )
655- {
656- self . dropped_total += 1 ;
687+ if let Some ( c) = self . connections . get_mut ( & id) {
688+ c. phase . close ( ) ;
657689 }
658690 self . send_queues . remove ( & id) ;
659691 return false ;
@@ -852,10 +884,26 @@ async fn handle_tcp_connection(
852884
853885/// Generic over the socket transport so unix + TCP share the logic.
854886async fn drive_connection < S > (
855- mut sock : S ,
887+ sock : S ,
856888 state : Arc < Mutex < ShadowStreamState > > ,
857889 flush_interval : Duration ,
858890) -> Result < ( ) , ShadowStreamError >
891+ where
892+ S : tokio:: io:: AsyncRead + tokio:: io:: AsyncWrite + Unpin + Send ,
893+ {
894+ let ended = serve_connection ( sock, state. clone ( ) , flush_interval) . await ;
895+ state. lock ( ) . await . note_disconnect ( match & ended {
896+ Ok ( reason) => * reason,
897+ Err ( _) => Disconnect :: Error ,
898+ } ) ;
899+ ended. map ( |_| ( ) )
900+ }
901+
902+ async fn serve_connection < S > (
903+ mut sock : S ,
904+ state : Arc < Mutex < ShadowStreamState > > ,
905+ flush_interval : Duration ,
906+ ) -> Result < Disconnect , ShadowStreamError >
859907where
860908 S : tokio:: io:: AsyncRead + tokio:: io:: AsyncWrite + Unpin + Send ,
861909{
@@ -889,7 +937,7 @@ where
889937 let mut err = bytes:: BytesMut :: new ( ) ;
890938 server:: encode_error_response ( & mut err, refused. sqlstate ( ) , & refused. to_string ( ) ) ;
891939 conn. write_framed ( & err) . await ?;
892- return Ok ( ( ) ) ;
940+ return Ok ( Disconnect :: Error ) ;
893941 }
894942 } ;
895943 tracing:: info!(
@@ -903,7 +951,8 @@ where
903951 let outcome = run_connection_loop ( & mut conn, state. clone ( ) , id, flush_interval) . await ;
904952 state. lock ( ) . await . drop_connection ( id) ;
905953 match outcome? {
906- StreamOutcome :: Closed => return Ok ( ( ) ) ,
954+ StreamOutcome :: Closed => return Ok ( Disconnect :: ClientClosed ) ,
955+ StreamOutcome :: Slow => return Ok ( Disconnect :: SlowClient ) ,
907956 StreamOutcome :: TimelineEnded ( switch) => {
908957 conn. end_timeline ( switch) . await ?;
909958 let identity = state. lock ( ) . await . identity ( ) ;
@@ -915,8 +964,10 @@ where
915964
916965/// How one stream on a walsender connection finished.
917966enum StreamOutcome {
918- /// Client gone, or the connection dropped for slowness
967+ /// Client gone
919968 Closed ,
969+ /// Dropped for overflowing `slow_threshold`
970+ Slow ,
920971 /// Served through a historic branch's switchpoint; the client is owed the
921972 /// next-timeline result
922973 TimelineEnded ( TimelineSwitch ) ,
@@ -1009,7 +1060,7 @@ where
10091060 return Ok ( StreamOutcome :: TimelineEnded ( switch) ) ;
10101061 }
10111062 if closing {
1012- return Ok ( StreamOutcome :: Closed ) ;
1063+ return Ok ( StreamOutcome :: Slow ) ;
10131064 }
10141065 }
10151066}
@@ -1275,7 +1326,6 @@ mod tests {
12751326 assert ! ( !s. enqueue( id, vec![ 0u8 ; 64 ] ) ) ;
12761327 assert ! ( s. connections[ & id] . phase. is_closing( ) ) ;
12771328 assert ! ( !s. send_queues. contains_key( & id) ) ;
1278- assert_eq ! ( s. aggregate( ) . dropped_total, 1 ) ;
12791329 }
12801330
12811331 #[ test]
@@ -1295,16 +1345,6 @@ mod tests {
12951345 assert_eq ! ( s. timeline_ended_for( id) , Some ( switch) ) ;
12961346 }
12971347
1298- #[ test]
1299- fn dropped_total_increments_once_per_connection ( ) {
1300- let mut s = ShadowStreamState :: new ( 1 , "x" . into ( ) , 0 , 64 ) ;
1301- let id = s. register_connection ( 0 , 1 , None ) . expect ( "current timeline" ) ;
1302- assert ! ( !s. enqueue( id, vec![ 0u8 ; 128 ] ) ) ;
1303- // second overflow on the closing slot must not double-count
1304- assert ! ( !s. enqueue( id, vec![ 0u8 ; 128 ] ) ) ;
1305- assert_eq ! ( s. aggregate( ) . dropped_total, 1 ) ;
1306- }
1307-
13081348 #[ tokio:: test( flavor = "current_thread" ) ]
13091349 async fn sink_dispatches_one_wire_chunk_per_active_connection ( ) {
13101350 let state = Arc :: new ( Mutex :: new ( fresh_state ( ) ) ) ;
@@ -1405,6 +1445,49 @@ mod tests {
14051445 }
14061446 }
14071447
1448+ #[ tokio:: test( flavor = "current_thread" ) ]
1449+ async fn backfill_is_counted_and_starts_below_the_buffer_are_refused ( ) {
1450+ let state = Arc :: new ( Mutex :: new ( fresh_state ( ) ) ) ;
1451+ let mut sink = ShadowStreamSink :: new ( state. clone ( ) ) ;
1452+ sink. on_wire_chunk ( 0x1000 , b"AAAA" ) . await . unwrap ( ) ;
1453+ sink. on_segment_retired ( 0x1004 ) . await . unwrap ( ) ;
1454+ sink. on_wire_chunk ( 0x1004 , b"CCCC" ) . await . unwrap ( ) ;
1455+ let mut s = state. lock ( ) . await ;
1456+ s. register_connection ( 0x1008 , 1 , None ) . unwrap ( ) ;
1457+ assert_eq ! ( s. aggregate( ) . backfill_bytes_total, 0 ) ;
1458+ s. register_connection ( 0x1004 , 1 , None ) . unwrap ( ) ;
1459+ assert_eq ! ( s. aggregate( ) . backfill_bytes_total, 4 ) ;
1460+ assert ! ( matches!(
1461+ s. register_connection( 0x1000 , 1 , None ) ,
1462+ Err ( Refused :: Archived { .. } )
1463+ ) ) ;
1464+ assert_eq ! ( s. aggregate( ) . backfill_bytes_total, 4 ) ;
1465+ }
1466+
1467+ /// A rebuilt `WalStream` replays its segment over retained bytes, which
1468+ /// keeps `wire_buf_start` and the backfill gap-free
1469+ #[ test]
1470+ fn send_queue_bytes_is_the_largest_queue ( ) {
1471+ let mut s = ShadowStreamState :: new ( 1 , "x" . into ( ) , 0 , 64 ) ;
1472+ let a = s. register_connection ( 0 , 1 , None ) . unwrap ( ) ;
1473+ let b = s. register_connection ( 0 , 1 , None ) . unwrap ( ) ;
1474+ assert ! ( s. enqueue( a, vec![ 0u8 ; 10 ] ) ) ;
1475+ assert ! ( s. enqueue( b, vec![ 0u8 ; 30 ] ) ) ;
1476+ assert_eq ! ( s. aggregate( ) . send_queue_bytes, 30 ) ;
1477+ s. drain_send_queue ( b) ;
1478+ assert_eq ! ( s. aggregate( ) . send_queue_bytes, 10 ) ;
1479+ }
1480+
1481+ #[ test]
1482+ fn disconnects_count_per_reason ( ) {
1483+ let mut s = fresh_state ( ) ;
1484+ s. note_disconnect ( Disconnect :: SlowClient ) ;
1485+ s. note_disconnect ( Disconnect :: ClientClosed ) ;
1486+ s. note_disconnect ( Disconnect :: ClientClosed ) ;
1487+ s. note_disconnect ( Disconnect :: Error ) ;
1488+ assert_eq ! ( s. aggregate( ) . disconnects_total, [ 1 , 2 , 1 ] ) ;
1489+ }
1490+
14081491 /// A rebuilt `WalStream` replays its segment over retained bytes, which
14091492 /// keeps `wire_buf_start` and the backfill gap-free
14101493 #[ tokio:: test( flavor = "current_thread" ) ]
@@ -1428,9 +1511,9 @@ mod tests {
14281511 s. dispatch_wire ( 16 , b"EEEEEEEE" ) ;
14291512 s. swap_send_queue ( id, & mut Vec :: new ( ) ) ;
14301513 s. dispatch_wire ( 24 , b"FFFFFFFF" ) ;
1431- assert_eq ! ( s . aggregate ( ) . dropped_total , 0 ) ;
1514+ assert ! ( !s . connections [ & id ] . phase . is_closing ( ) ) ;
14321515 s. dispatch_wire ( 32 , b"GGGGGGGG" ) ;
1433- assert_eq ! ( s. aggregate ( ) . dropped_total , 1 ) ;
1516+ assert ! ( s. connections [ & id ] . phase . is_closing ( ) ) ;
14341517 }
14351518
14361519 #[ tokio:: test( flavor = "current_thread" ) ]
0 commit comments