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;
@@ -179,6 +180,10 @@ pub fn spawn_membership_worker(
179180
180181 let index = GatewayMemberIndex :: new ( state. store . clone ( ) , MEMBER_TTL ) ;
181182 let replica_id = state. replica_id . clone ( ) ;
183+ // Export the ring's size now (empty until the first refresh), so only
184+ // replicas that join the ring carry the gauge, and they carry it from the
185+ // start.
186+ publish_ring ( & state, GatewayRing :: clone) ;
182187
183188 Some ( tokio:: spawn ( async move {
184189 let mut ticker = tokio:: time:: interval ( interval) ;
@@ -209,9 +214,7 @@ pub fn spawn_membership_worker(
209214 . into_iter ( )
210215 . map ( |member| ( member. replica_id , member. peer_endpoint ) )
211216 . collect ( ) ;
212- if let Ok ( mut slot) = state. gateway_ring . write ( ) {
213- * slot = ring;
214- }
217+ publish_ring ( & state, |_| ring) ;
215218 if let Ok ( mut slot) = state. gateway_peers . write ( ) {
216219 * slot = peers;
217220 }
@@ -242,24 +245,18 @@ async fn leave_ring(state: &crate::ServerState, index: &GatewayMemberIndex, repl
242245 . into_iter ( )
243246 . map ( |member| ( member. replica_id , member. peer_endpoint ) )
244247 . collect ( ) ;
245- if let Ok ( mut slot) = state. gateway_ring . write ( ) {
246- * slot = ring. without ( replica_id) ;
247- }
248+ publish_ring ( state, |_| ring. without ( replica_id) ) ;
248249 if let Ok ( mut slot) = state. gateway_peers . write ( ) {
249250 * slot = peers;
250251 }
251252 }
252253 Ok ( Err ( error) ) => {
253254 tracing:: warn!( %error, "gateway membership: shutdown ring refresh failed" ) ;
254- if let Ok ( mut slot) = state. gateway_ring . write ( ) {
255- * slot = slot. without ( replica_id) ;
256- }
255+ publish_ring ( state, |ring| ring. without ( replica_id) ) ;
257256 }
258257 Err ( _) => {
259258 tracing:: warn!( "gateway membership: shutdown ring refresh timed out" ) ;
260- if let Ok ( mut slot) = state. gateway_ring . write ( ) {
261- * slot = slot. without ( replica_id) ;
262- }
259+ publish_ring ( state, |ring| ring. without ( replica_id) ) ;
263260 }
264261 }
265262 match tokio:: time:: timeout ( SHUTDOWN_STORE_TIMEOUT , index. deregister ( replica_id) ) . await {
@@ -273,14 +270,26 @@ fn clear_ring_if_stale(state: &crate::ServerState, last_refreshed: tokio::time::
273270 if last_refreshed. elapsed ( ) <= MEMBER_TTL {
274271 return ;
275272 }
276- if let Ok ( mut slot) = state. gateway_ring . write ( ) {
277- * slot = GatewayRing :: default ( ) ;
278- }
273+ publish_ring ( state, |_| GatewayRing :: default ( ) ) ;
279274 if let Ok ( mut slot) = state. gateway_peers . write ( ) {
280275 slot. clear ( ) ;
281276 }
282277}
283278
279+ /// Replace this replica's placement ring with `next(current ring)` and record
280+ /// its size as `openshell_server_gateway_ring_members` under the same write
281+ /// lock.
282+ ///
283+ /// This is the only sanctioned non-test writer of `ServerState::gateway_ring`:
284+ /// writing the slot anywhere else lets the gauge drift from the ring. A
285+ /// poisoned lock leaves both unchanged.
286+ fn publish_ring ( state : & crate :: ServerState , next : impl FnOnce ( & GatewayRing ) -> GatewayRing ) {
287+ if let Ok ( mut slot) = state. gateway_ring . write ( ) {
288+ * slot = next ( & slot) ;
289+ gateway_metrics:: record_gateway_ring_members ( slot. replica_count ( ) ) ;
290+ }
291+ }
292+
284293#[ cfg( test) ]
285294mod tests {
286295 use super :: * ;
@@ -307,6 +316,7 @@ mod tests {
307316
308317 #[ tokio:: test]
309318 async fn leaving_points_ring_at_new_replicas_and_not_departed_ones ( ) {
319+ let metrics = gateway_metrics:: MetricsCapture :: install ( ) ;
310320 let state = crate :: grpc:: test_support:: test_server_state ( ) . await ;
311321 let index = GatewayMemberIndex :: new ( state. store . clone ( ) , MEMBER_TTL ) ;
312322 index. register ( "gw-old" , "https://gw-old" ) . await . unwrap ( ) ;
@@ -324,6 +334,10 @@ mod tests {
324334
325335 let ring = state. gateway_ring . read ( ) . unwrap ( ) . clone ( ) ;
326336 assert_eq ! ( ring. owner_for( "sb-1" ) , Some ( "gw-new" ) ) ;
337+ assert_eq ! (
338+ metrics. value( gateway_metrics:: GATEWAY_RING_MEMBERS ) ,
339+ Some ( 1 )
340+ ) ;
327341 assert_eq ! (
328342 state
329343 . gateway_peers
@@ -343,6 +357,215 @@ mod tests {
343357 assert_eq ! ( remaining, vec![ "gw-new" ] ) ;
344358 }
345359
360+ #[ tokio:: test]
361+ async fn leaving_without_a_membership_read_keeps_the_cached_ring_without_this_replica ( ) {
362+ let metrics = gateway_metrics:: MetricsCapture :: install ( ) ;
363+ let state = crate :: grpc:: test_support:: test_server_state ( ) . await ;
364+ publish_ring ( & state, |_| GatewayRing :: new ( [ "gw-a" , "gw-stopping" ] ) ) ;
365+ // Only the index's store is closed, so the shutdown membership read
366+ // fails while the state's store stays open.
367+ let store = Arc :: new ( crate :: persistence:: test_store ( ) . await ) ;
368+ store. close ( ) . await ;
369+ let index = GatewayMemberIndex :: new ( store, MEMBER_TTL ) ;
370+
371+ leave_ring ( & state, & index, "gw-stopping" ) . await ;
372+
373+ let ring = state. gateway_ring . read ( ) . unwrap ( ) . clone ( ) ;
374+ assert_eq ! ( ring. owner_for( "sb-1" ) , Some ( "gw-a" ) ) ;
375+ assert_eq ! (
376+ metrics. value( gateway_metrics:: GATEWAY_RING_MEMBERS ) ,
377+ Some ( 1 )
378+ ) ;
379+ }
380+
381+ #[ tokio:: test]
382+ async fn leaving_after_a_timed_out_membership_read_keeps_the_cached_ring_without_this_replica ( )
383+ {
384+ let metrics = gateway_metrics:: MetricsCapture :: install ( ) ;
385+ let state = crate :: grpc:: test_support:: test_server_state ( ) . await ;
386+ publish_ring ( & state, |_| GatewayRing :: new ( [ "gw-a" , "gw-stopping" ] ) ) ;
387+ // The listener accepts TCP but never answers the PostgreSQL handshake, so
388+ // the shutdown read hangs past SHUTDOWN_STORE_TIMEOUT instead of failing.
389+ let silent = tokio:: net:: TcpListener :: bind ( "127.0.0.1:0" ) . await . unwrap ( ) ;
390+ let url = format ! (
391+ "postgres://openshell@127.0.0.1:{}/openshell" ,
392+ silent. local_addr( ) . unwrap( ) . port( )
393+ ) ;
394+ let index = GatewayMemberIndex :: new (
395+ Arc :: new ( Store :: Postgres (
396+ crate :: persistence:: PostgresStore :: connect_lazy_for_tests ( & url, 1 ) ,
397+ ) ) ,
398+ MEMBER_TTL ,
399+ ) ;
400+
401+ // The paused clock jumps to each timeout while the socket stays silent.
402+ tokio:: time:: pause ( ) ;
403+ let started = tokio:: time:: Instant :: now ( ) ;
404+ leave_ring ( & state, & index, "gw-stopping" ) . await ;
405+ // Both the read and the deregister must hit their timeouts; a read that
406+ // failed fast would take the Ok(Err) branch and finish sooner.
407+ assert ! (
408+ started. elapsed( ) >= SHUTDOWN_STORE_TIMEOUT * 2 ,
409+ "the membership read must time out, not fail fast"
410+ ) ;
411+
412+ let ring = state. gateway_ring . read ( ) . unwrap ( ) . clone ( ) ;
413+ assert_eq ! ( ring. replica_count( ) , 1 ) ;
414+ assert_eq ! ( ring. owner_for( "sb-1" ) , Some ( "gw-a" ) ) ;
415+ assert_eq ! (
416+ metrics. value( gateway_metrics:: GATEWAY_RING_MEMBERS ) ,
417+ Some ( 1 )
418+ ) ;
419+ drop ( silent) ;
420+ }
421+
422+ #[ tokio:: test]
423+ async fn stale_ring_is_cleared_only_after_the_member_ttl ( ) {
424+ let metrics = gateway_metrics:: MetricsCapture :: install ( ) ;
425+ let state = crate :: grpc:: test_support:: test_server_state ( ) . await ;
426+ publish_ring ( & state, |_| GatewayRing :: new ( [ "gw-a" , "gw-b" ] ) ) ;
427+ * state. gateway_peers . write ( ) . unwrap ( ) = HashMap :: from ( [
428+ ( "gw-a" . to_string ( ) , "https://gw-a" . to_string ( ) ) ,
429+ ( "gw-b" . to_string ( ) , "https://gw-b" . to_string ( ) ) ,
430+ ] ) ;
431+ assert_eq ! (
432+ metrics. value( gateway_metrics:: GATEWAY_RING_MEMBERS ) ,
433+ Some ( 2 )
434+ ) ;
435+
436+ clear_ring_if_stale ( & state, tokio:: time:: Instant :: now ( ) ) ;
437+ assert_eq ! ( state. gateway_ring. read( ) . unwrap( ) . replica_count( ) , 2 ) ;
438+ assert_eq ! ( state. gateway_peers. read( ) . unwrap( ) . len( ) , 2 ) ;
439+ assert_eq ! (
440+ metrics. value( gateway_metrics:: GATEWAY_RING_MEMBERS ) ,
441+ Some ( 2 )
442+ ) ;
443+
444+ let last_refreshed = tokio:: time:: Instant :: now ( )
445+ . checked_sub ( MEMBER_TTL + Duration :: from_millis ( 1 ) )
446+ . expect ( "the monotonic clock is past one member TTL" ) ;
447+ clear_ring_if_stale ( & state, last_refreshed) ;
448+ assert ! ( state. gateway_ring. read( ) . unwrap( ) . is_empty( ) ) ;
449+ assert ! ( state. gateway_peers. read( ) . unwrap( ) . is_empty( ) ) ;
450+ assert_eq ! (
451+ metrics. value( gateway_metrics:: GATEWAY_RING_MEMBERS ) ,
452+ Some ( 0 )
453+ ) ;
454+ }
455+
456+ #[ tokio:: test]
457+ async fn poisoned_ring_lock_publishes_no_ring_size ( ) {
458+ let metrics = gateway_metrics:: MetricsCapture :: install ( ) ;
459+ let state = crate :: grpc:: test_support:: test_server_state ( ) . await ;
460+ let ring = Arc :: clone ( & state. gateway_ring ) ;
461+ let _ = std:: thread:: spawn ( move || {
462+ let _guard = ring. write ( ) . unwrap ( ) ;
463+ panic ! ( "poison the placement ring lock" ) ;
464+ } )
465+ . join ( ) ;
466+ assert ! ( state. gateway_ring. is_poisoned( ) ) ;
467+
468+ publish_ring ( & state, |_| GatewayRing :: new ( [ "gw-a" , "gw-b" ] ) ) ;
469+
470+ assert_eq ! ( metrics. value( gateway_metrics:: GATEWAY_RING_MEMBERS ) , None ) ;
471+ }
472+
473+ #[ tokio:: test]
474+ async fn single_replica_store_neither_joins_the_ring_nor_exports_its_size ( ) {
475+ let metrics = gateway_metrics:: MetricsCapture :: install ( ) ;
476+ let mut state = crate :: grpc:: test_support:: test_server_state ( ) . await ;
477+ // SQLite keeps the replica out even with a peer endpoint.
478+ Arc :: get_mut ( & mut state)
479+ . expect ( "test state is not shared yet" )
480+ . peer_endpoint = Some ( "http://gw-self:8081" . to_string ( ) ) ;
481+ let ( _shutdown_tx, shutdown_rx) = tokio:: sync:: watch:: channel ( false ) ;
482+
483+ assert ! ( spawn_membership_worker( state, MEMBER_REFRESH_INTERVAL , shutdown_rx) . is_none( ) ) ;
484+ assert_eq ! ( metrics. value( gateway_metrics:: GATEWAY_RING_MEMBERS ) , None ) ;
485+ }
486+
487+ #[ tokio:: test]
488+ #[ ignore = "requires a disposable PostgreSQL database in OPENSHELL_TEST_POSTGRES_URL; run mise run test:rust:postgres" ]
489+ async fn postgres_replica_without_peer_endpoint_neither_joins_the_ring_nor_exports_its_size ( ) {
490+ let metrics = gateway_metrics:: MetricsCapture :: install ( ) ;
491+ let schema =
492+ crate :: persistence:: test_postgres:: TestSchema :: create ( "membership_no_peer" ) . await ;
493+ let mut state =
494+ crate :: grpc:: test_support:: test_server_state_for_store ( schema. connect_store ( ) . await )
495+ . await ;
496+ // peer_endpoint is env-derived; pin it so the test does not depend on the environment.
497+ Arc :: get_mut ( & mut state)
498+ . expect ( "test state is not shared yet" )
499+ . peer_endpoint = None ;
500+ let ( _shutdown_tx, shutdown_rx) = tokio:: sync:: watch:: channel ( false ) ;
501+
502+ assert ! (
503+ spawn_membership_worker( state. clone( ) , MEMBER_REFRESH_INTERVAL , shutdown_rx) . is_none( )
504+ ) ;
505+ assert_eq ! ( metrics. value( gateway_metrics:: GATEWAY_RING_MEMBERS ) , None ) ;
506+ assert ! (
507+ !metrics
508+ . render( )
509+ . contains( gateway_metrics:: GATEWAY_RING_MEMBERS )
510+ ) ;
511+
512+ state. store . close ( ) . await ;
513+ schema. drop_schema ( ) . await ;
514+ }
515+
516+ #[ tokio:: test]
517+ #[ ignore = "requires a disposable PostgreSQL database in OPENSHELL_TEST_POSTGRES_URL; run mise run test:rust:postgres" ]
518+ async fn postgres_membership_worker_exports_ring_size ( ) {
519+ let metrics = gateway_metrics:: MetricsCapture :: install ( ) ;
520+ let schema =
521+ crate :: persistence:: test_postgres:: TestSchema :: create ( "membership_worker" ) . await ;
522+ let mut state =
523+ crate :: grpc:: test_support:: test_server_state_for_store ( schema. connect_store ( ) . await )
524+ . await ;
525+ {
526+ let state = Arc :: get_mut ( & mut state) . expect ( "test state is not shared yet" ) ;
527+ state. replica_id = "gw-self" . to_string ( ) ;
528+ state. peer_endpoint = Some ( "http://gw-self:8081" . to_string ( ) ) ;
529+ }
530+ GatewayMemberIndex :: new ( state. store . clone ( ) , MEMBER_TTL )
531+ . register ( "gw-other" , "http://gw-other:8081" )
532+ . await
533+ . unwrap ( ) ;
534+ let ( shutdown_tx, shutdown_rx) = tokio:: sync:: watch:: channel ( false ) ;
535+
536+ let worker = spawn_membership_worker ( state. clone ( ) , Duration :: from_millis ( 50 ) , shutdown_rx)
537+ . expect ( "a PostgreSQL replica with a peer endpoint joins the ring" ) ;
538+ assert_eq ! (
539+ metrics. value( gateway_metrics:: GATEWAY_RING_MEMBERS ) ,
540+ Some ( 0 )
541+ ) ;
542+
543+ tokio:: time:: timeout ( Duration :: from_secs ( 5 ) , async {
544+ while metrics. value ( gateway_metrics:: GATEWAY_RING_MEMBERS ) != Some ( 2 ) {
545+ tokio:: time:: sleep ( Duration :: from_millis ( 10 ) ) . await ;
546+ }
547+ } )
548+ . await
549+ . expect ( "the first refresh publishes both replicas" ) ;
550+ assert_eq ! ( state. gateway_ring. read( ) . unwrap( ) . replica_count( ) , 2 ) ;
551+
552+ // Leaving re-reads membership and keeps only the other replica.
553+ shutdown_tx. send ( true ) . unwrap ( ) ;
554+ tokio:: time:: timeout ( SHUTDOWN_MEMBERSHIP_TIMEOUT , worker)
555+ . await
556+ . expect ( "the worker leaves the ring" )
557+ . expect ( "membership worker task" ) ;
558+ let ring = state. gateway_ring . read ( ) . unwrap ( ) . clone ( ) ;
559+ assert_eq ! ( ring. owner_for( "sb-1" ) , Some ( "gw-other" ) ) ;
560+ assert_eq ! (
561+ metrics. value( gateway_metrics:: GATEWAY_RING_MEMBERS ) ,
562+ Some ( 1 )
563+ ) ;
564+
565+ state. store . close ( ) . await ;
566+ schema. drop_schema ( ) . await ;
567+ }
568+
346569 #[ tokio:: test]
347570 async fn register_is_idempotent_and_updates_the_endpoint ( ) {
348571 let index = test_index ( MEMBER_TTL ) . await ;
0 commit comments