88//! kept in the store rather than read from Kubernetes so it works for any
99//! multi-replica deployment and adds no API server load.
1010
11+ use crate :: gateway_metrics;
1112use crate :: gateway_ring:: GatewayRing ;
1213use crate :: persistence:: { PersistenceError , PersistenceResult , Store , WriteCondition } ;
1314use openshell_core:: time:: now_ms;
@@ -194,6 +195,10 @@ pub fn spawn_membership_worker(
194195
195196 let index = GatewayMemberIndex :: new ( state. store . clone ( ) , MEMBER_TTL ) ;
196197 let replica_id = state. replica_id . clone ( ) ;
198+ // Export the ring's size now (empty until the first refresh), so only
199+ // replicas that join the ring carry the gauge, and they carry it from the
200+ // start.
201+ publish_ring ( & state, GatewayRing :: clone) ;
197202
198203 Some ( tokio:: spawn ( async move {
199204 let mut ticker = tokio:: time:: interval ( interval) ;
@@ -227,9 +232,7 @@ pub fn spawn_membership_worker(
227232 . into_iter ( )
228233 . map ( |member| ( member. replica_id , member. peer_endpoint ) )
229234 . collect ( ) ;
230- if let Ok ( mut slot) = state. gateway_ring . write ( ) {
231- * slot = ring;
232- }
235+ publish_ring ( & state, |_| ring) ;
233236 if let Ok ( mut slot) = state. gateway_peers . write ( ) {
234237 * slot = peers;
235238 }
@@ -260,24 +263,18 @@ async fn leave_ring(state: &crate::ServerState, index: &GatewayMemberIndex, repl
260263 . into_iter ( )
261264 . map ( |member| ( member. replica_id , member. peer_endpoint ) )
262265 . collect ( ) ;
263- if let Ok ( mut slot) = state. gateway_ring . write ( ) {
264- * slot = ring. without ( replica_id) ;
265- }
266+ publish_ring ( state, |_| ring. without ( replica_id) ) ;
266267 if let Ok ( mut slot) = state. gateway_peers . write ( ) {
267268 * slot = peers;
268269 }
269270 }
270271 Ok ( Err ( error) ) => {
271272 tracing:: warn!( %error, "gateway membership: shutdown ring refresh failed" ) ;
272- if let Ok ( mut slot) = state. gateway_ring . write ( ) {
273- * slot = slot. without ( replica_id) ;
274- }
273+ publish_ring ( state, |ring| ring. without ( replica_id) ) ;
275274 }
276275 Err ( _) => {
277276 tracing:: warn!( "gateway membership: shutdown ring refresh timed out" ) ;
278- if let Ok ( mut slot) = state. gateway_ring . write ( ) {
279- * slot = slot. without ( replica_id) ;
280- }
277+ publish_ring ( state, |ring| ring. without ( replica_id) ) ;
281278 }
282279 }
283280 match tokio:: time:: timeout ( SHUTDOWN_STORE_TIMEOUT , index. deregister ( replica_id) ) . await {
@@ -291,14 +288,26 @@ fn clear_ring_if_stale(state: &crate::ServerState, last_refreshed: tokio::time::
291288 if last_refreshed. elapsed ( ) <= MEMBER_TTL {
292289 return ;
293290 }
294- if let Ok ( mut slot) = state. gateway_ring . write ( ) {
295- * slot = GatewayRing :: default ( ) ;
296- }
291+ publish_ring ( state, |_| GatewayRing :: default ( ) ) ;
297292 if let Ok ( mut slot) = state. gateway_peers . write ( ) {
298293 slot. clear ( ) ;
299294 }
300295}
301296
297+ /// Replace this replica's placement ring with `next(current ring)` and record
298+ /// its size as `openshell_server_gateway_ring_members` under the same write
299+ /// lock.
300+ ///
301+ /// This is the only sanctioned non-test writer of `ServerState::gateway_ring`:
302+ /// writing the slot anywhere else lets the gauge drift from the ring. A
303+ /// poisoned lock leaves both unchanged.
304+ fn publish_ring ( state : & crate :: ServerState , next : impl FnOnce ( & GatewayRing ) -> GatewayRing ) {
305+ if let Ok ( mut slot) = state. gateway_ring . write ( ) {
306+ * slot = next ( & slot) ;
307+ gateway_metrics:: record_gateway_ring_members ( slot. replica_count ( ) ) ;
308+ }
309+ }
310+
302311#[ cfg( test) ]
303312mod tests {
304313 use super :: * ;
@@ -325,6 +334,7 @@ mod tests {
325334
326335 #[ tokio:: test]
327336 async fn leaving_points_ring_at_new_replicas_and_not_departed_ones ( ) {
337+ let metrics = gateway_metrics:: MetricsCapture :: install ( ) ;
328338 let state = crate :: grpc:: test_support:: test_server_state ( ) . await ;
329339 let index = GatewayMemberIndex :: new ( state. store . clone ( ) , MEMBER_TTL ) ;
330340 index. register ( "gw-old" , "https://gw-old" ) . await . unwrap ( ) ;
@@ -342,6 +352,10 @@ mod tests {
342352
343353 let ring = state. gateway_ring . read ( ) . unwrap ( ) . clone ( ) ;
344354 assert_eq ! ( ring. owner_for( "sb-1" ) , Some ( "gw-new" ) ) ;
355+ assert_eq ! (
356+ metrics. value( gateway_metrics:: GATEWAY_RING_MEMBERS ) ,
357+ Some ( 1 )
358+ ) ;
345359 assert_eq ! (
346360 state
347361 . gateway_peers
@@ -361,6 +375,222 @@ mod tests {
361375 assert_eq ! ( remaining, vec![ "gw-new" ] ) ;
362376 }
363377
378+ #[ tokio:: test]
379+ async fn leaving_without_a_membership_read_keeps_the_cached_ring_without_this_replica ( ) {
380+ let metrics = gateway_metrics:: MetricsCapture :: install ( ) ;
381+ let state = crate :: grpc:: test_support:: test_server_state ( ) . await ;
382+ publish_ring ( & state, |_| GatewayRing :: new ( [ "gw-a" , "gw-stopping" ] ) ) ;
383+ // Only the index's store is closed, so the shutdown membership read
384+ // fails while the state's store stays open.
385+ let store = Arc :: new ( crate :: persistence:: test_store ( ) . await ) ;
386+ store. close ( ) . await ;
387+ let index = GatewayMemberIndex :: new ( store, MEMBER_TTL ) ;
388+
389+ leave_ring ( & state, & index, "gw-stopping" ) . await ;
390+
391+ let ring = state. gateway_ring . read ( ) . unwrap ( ) . clone ( ) ;
392+ assert_eq ! ( ring. owner_for( "sb-1" ) , Some ( "gw-a" ) ) ;
393+ assert_eq ! (
394+ metrics. value( gateway_metrics:: GATEWAY_RING_MEMBERS ) ,
395+ Some ( 1 )
396+ ) ;
397+ }
398+
399+ #[ tokio:: test]
400+ async fn leaving_after_a_timed_out_membership_read_keeps_the_cached_ring_without_this_replica ( )
401+ {
402+ let metrics = gateway_metrics:: MetricsCapture :: install ( ) ;
403+ let state = crate :: grpc:: test_support:: test_server_state ( ) . await ;
404+ publish_ring ( & state, |_| GatewayRing :: new ( [ "gw-a" , "gw-stopping" ] ) ) ;
405+ // The listener accepts TCP but never answers the PostgreSQL handshake, so
406+ // the shutdown read hangs past SHUTDOWN_STORE_TIMEOUT instead of failing.
407+ let silent = tokio:: net:: TcpListener :: bind ( "127.0.0.1:0" ) . await . unwrap ( ) ;
408+ let url = format ! (
409+ "postgres://openshell@127.0.0.1:{}/openshell" ,
410+ silent. local_addr( ) . unwrap( ) . port( )
411+ ) ;
412+ let index = GatewayMemberIndex :: new (
413+ Arc :: new ( Store :: Postgres (
414+ crate :: persistence:: PostgresStore :: connect_lazy_for_tests ( & url, 1 ) ,
415+ ) ) ,
416+ MEMBER_TTL ,
417+ ) ;
418+
419+ // The paused clock jumps to each timeout while the socket stays silent.
420+ tokio:: time:: pause ( ) ;
421+ let started = tokio:: time:: Instant :: now ( ) ;
422+ leave_ring ( & state, & index, "gw-stopping" ) . await ;
423+ // Both the read and the deregister must hit their timeouts; a read that
424+ // failed fast would take the Ok(Err) branch and finish sooner.
425+ assert ! (
426+ started. elapsed( ) >= SHUTDOWN_STORE_TIMEOUT * 2 ,
427+ "the membership read must time out, not fail fast"
428+ ) ;
429+
430+ let ring = state. gateway_ring . read ( ) . unwrap ( ) . clone ( ) ;
431+ assert_eq ! ( ring. replica_count( ) , 1 ) ;
432+ assert_eq ! ( ring. owner_for( "sb-1" ) , Some ( "gw-a" ) ) ;
433+ assert_eq ! (
434+ metrics. value( gateway_metrics:: GATEWAY_RING_MEMBERS ) ,
435+ Some ( 1 )
436+ ) ;
437+ drop ( silent) ;
438+ }
439+
440+ #[ tokio:: test]
441+ async fn stale_ring_is_cleared_only_after_the_member_ttl ( ) {
442+ let metrics = gateway_metrics:: MetricsCapture :: install ( ) ;
443+ let state = crate :: grpc:: test_support:: test_server_state ( ) . await ;
444+ publish_ring ( & state, |_| GatewayRing :: new ( [ "gw-a" , "gw-b" ] ) ) ;
445+ * state. gateway_peers . write ( ) . unwrap ( ) = HashMap :: from ( [
446+ ( "gw-a" . to_string ( ) , "https://gw-a" . to_string ( ) ) ,
447+ ( "gw-b" . to_string ( ) , "https://gw-b" . to_string ( ) ) ,
448+ ] ) ;
449+ assert_eq ! (
450+ metrics. value( gateway_metrics:: GATEWAY_RING_MEMBERS ) ,
451+ Some ( 2 )
452+ ) ;
453+
454+ clear_ring_if_stale ( & state, tokio:: time:: Instant :: now ( ) ) ;
455+ assert_eq ! ( state. gateway_ring. read( ) . unwrap( ) . replica_count( ) , 2 ) ;
456+ assert_eq ! ( state. gateway_peers. read( ) . unwrap( ) . len( ) , 2 ) ;
457+ assert_eq ! (
458+ metrics. value( gateway_metrics:: GATEWAY_RING_MEMBERS ) ,
459+ Some ( 2 )
460+ ) ;
461+
462+ let last_refreshed = tokio:: time:: Instant :: now ( )
463+ . checked_sub ( MEMBER_TTL + Duration :: from_millis ( 1 ) )
464+ . expect ( "the monotonic clock is past one member TTL" ) ;
465+ clear_ring_if_stale ( & state, last_refreshed) ;
466+ assert ! ( state. gateway_ring. read( ) . unwrap( ) . is_empty( ) ) ;
467+ assert ! ( state. gateway_peers. read( ) . unwrap( ) . is_empty( ) ) ;
468+ assert_eq ! (
469+ metrics. value( gateway_metrics:: GATEWAY_RING_MEMBERS ) ,
470+ Some ( 0 )
471+ ) ;
472+ }
473+
474+ #[ tokio:: test]
475+ async fn poisoned_ring_lock_publishes_no_ring_size ( ) {
476+ let metrics = gateway_metrics:: MetricsCapture :: install ( ) ;
477+ let state = crate :: grpc:: test_support:: test_server_state ( ) . await ;
478+ let ring = Arc :: clone ( & state. gateway_ring ) ;
479+ let poisoned = std:: thread:: spawn ( move || {
480+ std:: panic:: catch_unwind ( std:: panic:: AssertUnwindSafe ( || {
481+ let _guard = ring. write ( ) . unwrap ( ) ;
482+ // `resume_unwind` drops the guard and poisons the lock without
483+ // running the panic hook, keeping the expected panic out of
484+ // the test output.
485+ std:: panic:: resume_unwind ( Box :: new ( "poison the placement ring lock" ) ) ;
486+ } ) )
487+ } )
488+ . join ( )
489+ . expect ( "the poisoning thread should catch its own unwind" ) ;
490+ assert ! ( poisoned. is_err( ) ) ;
491+ assert ! ( state. gateway_ring. is_poisoned( ) ) ;
492+
493+ publish_ring ( & state, |_| GatewayRing :: new ( [ "gw-a" , "gw-b" ] ) ) ;
494+
495+ assert_eq ! ( metrics. value( gateway_metrics:: GATEWAY_RING_MEMBERS ) , None ) ;
496+ }
497+
498+ #[ tokio:: test]
499+ async fn single_replica_store_neither_joins_the_ring_nor_exports_its_size ( ) {
500+ let metrics = gateway_metrics:: MetricsCapture :: install ( ) ;
501+ let mut state = crate :: grpc:: test_support:: test_server_state ( ) . await ;
502+ // SQLite keeps the replica out even with a peer endpoint.
503+ Arc :: get_mut ( & mut state)
504+ . expect ( "test state is not shared yet" )
505+ . peer_endpoint = Some ( "http://gw-self:8081" . to_string ( ) ) ;
506+ let ( _shutdown_tx, shutdown_rx) = tokio:: sync:: watch:: channel ( false ) ;
507+
508+ assert ! ( spawn_membership_worker( state, MEMBER_REFRESH_INTERVAL , shutdown_rx) . is_none( ) ) ;
509+ assert_eq ! ( metrics. value( gateway_metrics:: GATEWAY_RING_MEMBERS ) , None ) ;
510+ }
511+
512+ #[ tokio:: test]
513+ #[ ignore = "requires a disposable PostgreSQL database in OPENSHELL_TEST_POSTGRES_URL; run mise run test:rust:postgres" ]
514+ async fn postgres_replica_without_peer_endpoint_neither_joins_the_ring_nor_exports_its_size ( ) {
515+ let metrics = gateway_metrics:: MetricsCapture :: install ( ) ;
516+ let schema =
517+ crate :: persistence:: test_postgres:: TestSchema :: create ( "membership_no_peer" ) . await ;
518+ let mut state =
519+ crate :: grpc:: test_support:: test_server_state_for_store ( schema. connect_store ( ) . await )
520+ . await ;
521+ // peer_endpoint is env-derived; pin it so the test does not depend on the environment.
522+ Arc :: get_mut ( & mut state)
523+ . expect ( "test state is not shared yet" )
524+ . peer_endpoint = None ;
525+ let ( _shutdown_tx, shutdown_rx) = tokio:: sync:: watch:: channel ( false ) ;
526+
527+ assert ! (
528+ spawn_membership_worker( state. clone( ) , MEMBER_REFRESH_INTERVAL , shutdown_rx) . is_none( )
529+ ) ;
530+ assert_eq ! ( metrics. value( gateway_metrics:: GATEWAY_RING_MEMBERS ) , None ) ;
531+ assert ! (
532+ !metrics
533+ . render( )
534+ . contains( gateway_metrics:: GATEWAY_RING_MEMBERS )
535+ ) ;
536+
537+ state. store . close ( ) . await ;
538+ schema. drop_schema ( ) . await ;
539+ }
540+
541+ #[ tokio:: test]
542+ #[ ignore = "requires a disposable PostgreSQL database in OPENSHELL_TEST_POSTGRES_URL; run mise run test:rust:postgres" ]
543+ async fn postgres_membership_worker_exports_ring_size ( ) {
544+ let metrics = gateway_metrics:: MetricsCapture :: install ( ) ;
545+ let schema =
546+ crate :: persistence:: test_postgres:: TestSchema :: create ( "membership_worker" ) . await ;
547+ let mut state =
548+ crate :: grpc:: test_support:: test_server_state_for_store ( schema. connect_store ( ) . await )
549+ . await ;
550+ {
551+ let state = Arc :: get_mut ( & mut state) . expect ( "test state is not shared yet" ) ;
552+ state. replica_id = "gw-self" . to_string ( ) ;
553+ state. peer_endpoint = Some ( "http://gw-self:8081" . to_string ( ) ) ;
554+ }
555+ GatewayMemberIndex :: new ( state. store . clone ( ) , MEMBER_TTL )
556+ . register ( "gw-other" , "http://gw-other:8081" )
557+ . await
558+ . unwrap ( ) ;
559+ let ( shutdown_tx, shutdown_rx) = tokio:: sync:: watch:: channel ( false ) ;
560+
561+ let worker = spawn_membership_worker ( state. clone ( ) , Duration :: from_millis ( 50 ) , shutdown_rx)
562+ . expect ( "a PostgreSQL replica with a peer endpoint joins the ring" ) ;
563+ assert_eq ! (
564+ metrics. value( gateway_metrics:: GATEWAY_RING_MEMBERS ) ,
565+ Some ( 0 )
566+ ) ;
567+
568+ tokio:: time:: timeout ( Duration :: from_secs ( 5 ) , async {
569+ while metrics. value ( gateway_metrics:: GATEWAY_RING_MEMBERS ) != Some ( 2 ) {
570+ tokio:: time:: sleep ( Duration :: from_millis ( 10 ) ) . await ;
571+ }
572+ } )
573+ . await
574+ . expect ( "the first refresh publishes both replicas" ) ;
575+ assert_eq ! ( state. gateway_ring. read( ) . unwrap( ) . replica_count( ) , 2 ) ;
576+
577+ // Leaving re-reads membership and keeps only the other replica.
578+ shutdown_tx. send ( true ) . unwrap ( ) ;
579+ tokio:: time:: timeout ( SHUTDOWN_MEMBERSHIP_TIMEOUT , worker)
580+ . await
581+ . expect ( "the worker leaves the ring" )
582+ . expect ( "membership worker task" ) ;
583+ let ring = state. gateway_ring . read ( ) . unwrap ( ) . clone ( ) ;
584+ assert_eq ! ( ring. owner_for( "sb-1" ) , Some ( "gw-other" ) ) ;
585+ assert_eq ! (
586+ metrics. value( gateway_metrics:: GATEWAY_RING_MEMBERS ) ,
587+ Some ( 1 )
588+ ) ;
589+
590+ state. store . close ( ) . await ;
591+ schema. drop_schema ( ) . await ;
592+ }
593+
364594 #[ tokio:: test]
365595 async fn register_is_idempotent_and_updates_the_endpoint ( ) {
366596 let index = test_index ( MEMBER_TTL ) . await ;
0 commit comments