LCOV - code coverage report
Current view: top level - storage_broker/src/bin - storage_broker.rs (source / functions) Coverage Total Hit
Test: 49aa928ec5b4b510172d8b5c6d154da28e70a46c.info Lines: 38.0 % 558 212
Test Date: 2024-11-13 18:23:39 Functions: 26.4 % 72 19

            Line data    Source code
       1              : //! Simple pub-sub based on grpc (tonic) and Tokio broadcast channel for storage
       2              : //! nodes messaging.
       3              : //!
       4              : //! Subscriptions to 1) single timeline 2) all timelines are possible. We could
       5              : //! add subscription to the set of timelines to save grpc streams, but testing
       6              : //! shows many individual streams is also ok.
       7              : //!
       8              : //! Message is dropped if subscriber can't consume it, not affecting other
       9              : //! subscribers.
      10              : //!
      11              : //! Only safekeeper message is supported, but it is not hard to add something
      12              : //! else with generics.
      13              : use clap::{command, Parser};
      14              : use futures_core::Stream;
      15              : use futures_util::StreamExt;
      16              : use http_body_util::Full;
      17              : use hyper::body::Incoming;
      18              : use hyper::header::CONTENT_TYPE;
      19              : use hyper::service::service_fn;
      20              : use hyper::{Method, StatusCode};
      21              : use hyper_util::rt::{TokioExecutor, TokioIo, TokioTimer};
      22              : use parking_lot::RwLock;
      23              : use std::collections::HashMap;
      24              : use std::convert::Infallible;
      25              : use std::net::SocketAddr;
      26              : use std::pin::Pin;
      27              : use std::sync::Arc;
      28              : use std::time::Duration;
      29              : use tokio::net::TcpListener;
      30              : use tokio::sync::broadcast;
      31              : use tokio::sync::broadcast::error::RecvError;
      32              : use tokio::time;
      33              : use tonic::body::{self, empty_body, BoxBody};
      34              : use tonic::codegen::Service;
      35              : use tonic::transport::server::Connected;
      36              : use tonic::Code;
      37              : use tonic::{Request, Response, Status};
      38              : use tracing::*;
      39              : use utils::signals::ShutdownSignals;
      40              : 
      41              : use metrics::{Encoder, TextEncoder};
      42              : use storage_broker::metrics::{
      43              :     BROADCASTED_MESSAGES_TOTAL, BROADCAST_DROPPED_MESSAGES_TOTAL, NUM_PUBS, NUM_SUBS_ALL,
      44              :     NUM_SUBS_TIMELINE, PROCESSED_MESSAGES_TOTAL, PUBLISHED_ONEOFF_MESSAGES_TOTAL,
      45              : };
      46              : use storage_broker::proto::broker_service_server::{BrokerService, BrokerServiceServer};
      47              : use storage_broker::proto::subscribe_safekeeper_info_request::SubscriptionKey as ProtoSubscriptionKey;
      48              : use storage_broker::proto::{
      49              :     FilterTenantTimelineId, MessageType, SafekeeperDiscoveryRequest, SafekeeperDiscoveryResponse,
      50              :     SafekeeperTimelineInfo, SubscribeByFilterRequest, SubscribeSafekeeperInfoRequest, TypedMessage,
      51              : };
      52              : use storage_broker::{parse_proto_ttid, DEFAULT_KEEPALIVE_INTERVAL, DEFAULT_LISTEN_ADDR};
      53              : use utils::id::TenantTimelineId;
      54              : use utils::logging::{self, LogFormat};
      55              : use utils::sentry_init::init_sentry;
      56              : use utils::{project_build_tag, project_git_version};
      57              : 
      58              : project_git_version!(GIT_VERSION);
      59              : project_build_tag!(BUILD_TAG);
      60              : 
      61              : const DEFAULT_CHAN_SIZE: usize = 32;
      62              : const DEFAULT_ALL_KEYS_CHAN_SIZE: usize = 16384;
      63              : 
      64            0 : #[derive(Parser, Debug)]
      65              : #[command(version = GIT_VERSION, about = "Broker for neon storage nodes communication", long_about = None)]
      66              : struct Args {
      67              :     /// Endpoint to listen on.
      68              :     #[arg(short, long, default_value = DEFAULT_LISTEN_ADDR)]
      69            0 :     listen_addr: SocketAddr,
      70              :     /// Size of the queue to the per timeline subscriber.
      71            0 :     #[arg(long, default_value_t = DEFAULT_CHAN_SIZE)]
      72            0 :     timeline_chan_size: usize,
      73              :     /// Size of the queue to the all keys subscriber.
      74            0 :     #[arg(long, default_value_t = DEFAULT_ALL_KEYS_CHAN_SIZE)]
      75            0 :     all_keys_chan_size: usize,
      76              :     /// HTTP/2 keepalive interval.
      77              :     #[arg(long, value_parser= humantime::parse_duration, default_value = DEFAULT_KEEPALIVE_INTERVAL)]
      78            0 :     http2_keepalive_interval: Duration,
      79              :     /// Format for logging, either 'plain' or 'json'.
      80              :     #[arg(long, default_value = "plain")]
      81            0 :     log_format: String,
      82              : }
      83              : 
      84              : /// Id of publisher for registering in maps
      85              : type PubId = u64;
      86              : 
      87              : /// Id of subscriber for registering in maps
      88              : type SubId = u64;
      89              : 
      90              : /// Single enum type for all messages.
      91              : #[derive(Clone, Debug, PartialEq)]
      92              : #[allow(clippy::enum_variant_names)]
      93              : enum Message {
      94              :     SafekeeperTimelineInfo(SafekeeperTimelineInfo),
      95              :     SafekeeperDiscoveryRequest(SafekeeperDiscoveryRequest),
      96              :     SafekeeperDiscoveryResponse(SafekeeperDiscoveryResponse),
      97              : }
      98              : 
      99              : impl Message {
     100              :     /// Convert proto message to internal message.
     101            0 :     pub fn from(proto_msg: TypedMessage) -> Result<Self, Status> {
     102            0 :         match proto_msg.r#type() {
     103              :             MessageType::SafekeeperTimelineInfo => Ok(Message::SafekeeperTimelineInfo(
     104            0 :                 proto_msg.safekeeper_timeline_info.ok_or_else(|| {
     105            0 :                     Status::new(Code::InvalidArgument, "missing safekeeper_timeline_info")
     106            0 :                 })?,
     107              :             )),
     108              :             MessageType::SafekeeperDiscoveryRequest => Ok(Message::SafekeeperDiscoveryRequest(
     109            0 :                 proto_msg.safekeeper_discovery_request.ok_or_else(|| {
     110            0 :                     Status::new(
     111            0 :                         Code::InvalidArgument,
     112            0 :                         "missing safekeeper_discovery_request",
     113            0 :                     )
     114            0 :                 })?,
     115              :             )),
     116              :             MessageType::SafekeeperDiscoveryResponse => Ok(Message::SafekeeperDiscoveryResponse(
     117            0 :                 proto_msg.safekeeper_discovery_response.ok_or_else(|| {
     118            0 :                     Status::new(
     119            0 :                         Code::InvalidArgument,
     120            0 :                         "missing safekeeper_discovery_response",
     121            0 :                     )
     122            0 :                 })?,
     123              :             )),
     124            0 :             MessageType::Unknown => Err(Status::new(
     125            0 :                 Code::InvalidArgument,
     126            0 :                 format!("invalid message type: {:?}", proto_msg.r#type),
     127            0 :             )),
     128              :         }
     129            0 :     }
     130              : 
     131              :     /// Get the tenant_timeline_id from the message.
     132            2 :     pub fn tenant_timeline_id(&self) -> Result<Option<TenantTimelineId>, Status> {
     133            2 :         match self {
     134            2 :             Message::SafekeeperTimelineInfo(msg) => Ok(msg
     135            2 :                 .tenant_timeline_id
     136            2 :                 .as_ref()
     137            2 :                 .map(parse_proto_ttid)
     138            2 :                 .transpose()?),
     139            0 :             Message::SafekeeperDiscoveryRequest(msg) => Ok(msg
     140            0 :                 .tenant_timeline_id
     141            0 :                 .as_ref()
     142            0 :                 .map(parse_proto_ttid)
     143            0 :                 .transpose()?),
     144            0 :             Message::SafekeeperDiscoveryResponse(msg) => Ok(msg
     145            0 :                 .tenant_timeline_id
     146            0 :                 .as_ref()
     147            0 :                 .map(parse_proto_ttid)
     148            0 :                 .transpose()?),
     149              :         }
     150            2 :     }
     151              : 
     152              :     /// Convert internal message to the protobuf struct.
     153            0 :     pub fn as_typed_message(&self) -> TypedMessage {
     154            0 :         let mut res = TypedMessage {
     155            0 :             r#type: self.message_type() as i32,
     156            0 :             ..Default::default()
     157            0 :         };
     158            0 :         match self {
     159            0 :             Message::SafekeeperTimelineInfo(msg) => {
     160            0 :                 res.safekeeper_timeline_info = Some(msg.clone())
     161              :             }
     162            0 :             Message::SafekeeperDiscoveryRequest(msg) => {
     163            0 :                 res.safekeeper_discovery_request = Some(msg.clone())
     164              :             }
     165            0 :             Message::SafekeeperDiscoveryResponse(msg) => {
     166            0 :                 res.safekeeper_discovery_response = Some(msg.clone())
     167              :             }
     168              :         }
     169            0 :         res
     170            0 :     }
     171              : 
     172              :     /// Get the message type.
     173            0 :     pub fn message_type(&self) -> MessageType {
     174            0 :         match self {
     175            0 :             Message::SafekeeperTimelineInfo(_) => MessageType::SafekeeperTimelineInfo,
     176            0 :             Message::SafekeeperDiscoveryRequest(_) => MessageType::SafekeeperDiscoveryRequest,
     177            0 :             Message::SafekeeperDiscoveryResponse(_) => MessageType::SafekeeperDiscoveryResponse,
     178              :         }
     179            0 :     }
     180              : }
     181              : 
     182              : #[derive(Copy, Clone, Debug)]
     183              : enum SubscriptionKey {
     184              :     All,
     185              :     Timeline(TenantTimelineId),
     186              : }
     187              : 
     188              : impl SubscriptionKey {
     189              :     /// Parse protobuf subkey (protobuf doesn't have fixed size bytes, we get vectors).
     190            0 :     pub fn from_proto_subscription_key(key: ProtoSubscriptionKey) -> Result<Self, Status> {
     191            0 :         match key {
     192            0 :             ProtoSubscriptionKey::All(_) => Ok(SubscriptionKey::All),
     193            0 :             ProtoSubscriptionKey::TenantTimelineId(proto_ttid) => {
     194            0 :                 Ok(SubscriptionKey::Timeline(parse_proto_ttid(&proto_ttid)?))
     195              :             }
     196              :         }
     197            0 :     }
     198              : 
     199              :     /// Parse from FilterTenantTimelineId
     200            0 :     pub fn from_proto_filter_tenant_timeline_id(
     201            0 :         opt: Option<&FilterTenantTimelineId>,
     202            0 :     ) -> Result<Self, Status> {
     203            0 :         if opt.is_none() {
     204            0 :             return Ok(SubscriptionKey::All);
     205            0 :         }
     206            0 : 
     207            0 :         let f = opt.unwrap();
     208            0 :         if !f.enabled {
     209            0 :             return Ok(SubscriptionKey::All);
     210            0 :         }
     211              : 
     212            0 :         let ttid =
     213            0 :             parse_proto_ttid(f.tenant_timeline_id.as_ref().ok_or_else(|| {
     214            0 :                 Status::new(Code::InvalidArgument, "missing tenant_timeline_id")
     215            0 :             })?)?;
     216            0 :         Ok(SubscriptionKey::Timeline(ttid))
     217            0 :     }
     218              : }
     219              : 
     220              : /// Channel to timeline subscribers.
     221              : struct ChanToTimelineSub {
     222              :     chan: broadcast::Sender<Message>,
     223              :     /// Tracked separately to know when delete the shmem entry. receiver_count()
     224              :     /// is unhandy for that as unregistering and dropping the receiver side
     225              :     /// happens at different moments.
     226              :     num_subscribers: u64,
     227              : }
     228              : 
     229              : struct SharedState {
     230              :     next_pub_id: PubId,
     231              :     num_pubs: i64,
     232              :     next_sub_id: SubId,
     233              :     num_subs_to_timelines: i64,
     234              :     chans_to_timeline_subs: HashMap<TenantTimelineId, ChanToTimelineSub>,
     235              :     num_subs_to_all: i64,
     236              :     chan_to_all_subs: broadcast::Sender<Message>,
     237              : }
     238              : 
     239              : impl SharedState {
     240            1 :     pub fn new(all_keys_chan_size: usize) -> Self {
     241            1 :         SharedState {
     242            1 :             next_pub_id: 0,
     243            1 :             num_pubs: 0,
     244            1 :             next_sub_id: 0,
     245            1 :             num_subs_to_timelines: 0,
     246            1 :             chans_to_timeline_subs: HashMap::new(),
     247            1 :             num_subs_to_all: 0,
     248            1 :             chan_to_all_subs: broadcast::channel(all_keys_chan_size).0,
     249            1 :         }
     250            1 :     }
     251              : 
     252              :     // Register new publisher.
     253            1 :     pub fn register_publisher(&mut self) -> PubId {
     254            1 :         let pub_id = self.next_pub_id;
     255            1 :         self.next_pub_id += 1;
     256            1 :         self.num_pubs += 1;
     257            1 :         NUM_PUBS.set(self.num_pubs);
     258            1 :         pub_id
     259            1 :     }
     260              : 
     261              :     // Unregister publisher.
     262            1 :     pub fn unregister_publisher(&mut self) {
     263            1 :         self.num_pubs -= 1;
     264            1 :         NUM_PUBS.set(self.num_pubs);
     265            1 :     }
     266              : 
     267              :     // Register new subscriber.
     268            2 :     pub fn register_subscriber(
     269            2 :         &mut self,
     270            2 :         sub_key: SubscriptionKey,
     271            2 :         timeline_chan_size: usize,
     272            2 :     ) -> (SubId, broadcast::Receiver<Message>) {
     273            2 :         let sub_id = self.next_sub_id;
     274            2 :         self.next_sub_id += 1;
     275            2 :         let sub_rx = match sub_key {
     276              :             SubscriptionKey::All => {
     277            1 :                 self.num_subs_to_all += 1;
     278            1 :                 NUM_SUBS_ALL.set(self.num_subs_to_all);
     279            1 :                 self.chan_to_all_subs.subscribe()
     280              :             }
     281            1 :             SubscriptionKey::Timeline(ttid) => {
     282            1 :                 self.num_subs_to_timelines += 1;
     283            1 :                 NUM_SUBS_TIMELINE.set(self.num_subs_to_timelines);
     284            1 :                 // Create new broadcast channel for this key, or subscriber to
     285            1 :                 // the existing one.
     286            1 :                 let chan_to_timeline_sub =
     287            1 :                     self.chans_to_timeline_subs
     288            1 :                         .entry(ttid)
     289            1 :                         .or_insert(ChanToTimelineSub {
     290            1 :                             chan: broadcast::channel(timeline_chan_size).0,
     291            1 :                             num_subscribers: 0,
     292            1 :                         });
     293            1 :                 chan_to_timeline_sub.num_subscribers += 1;
     294            1 :                 chan_to_timeline_sub.chan.subscribe()
     295              :             }
     296              :         };
     297            2 :         (sub_id, sub_rx)
     298            2 :     }
     299              : 
     300              :     // Unregister the subscriber.
     301            2 :     pub fn unregister_subscriber(&mut self, sub_key: SubscriptionKey) {
     302            2 :         match sub_key {
     303            1 :             SubscriptionKey::All => {
     304            1 :                 self.num_subs_to_all -= 1;
     305            1 :                 NUM_SUBS_ALL.set(self.num_subs_to_all);
     306            1 :             }
     307            1 :             SubscriptionKey::Timeline(ttid) => {
     308            1 :                 self.num_subs_to_timelines -= 1;
     309            1 :                 NUM_SUBS_TIMELINE.set(self.num_subs_to_timelines);
     310            1 : 
     311            1 :                 // Remove from the map, destroying the channel, if we are the
     312            1 :                 // last subscriber to this timeline.
     313            1 : 
     314            1 :                 // Missing entry is a bug; we must have registered.
     315            1 :                 let chan_to_timeline_sub = self
     316            1 :                     .chans_to_timeline_subs
     317            1 :                     .get_mut(&ttid)
     318            1 :                     .expect("failed to find sub entry in shmem during unregister");
     319            1 :                 chan_to_timeline_sub.num_subscribers -= 1;
     320            1 :                 if chan_to_timeline_sub.num_subscribers == 0 {
     321            1 :                     self.chans_to_timeline_subs.remove(&ttid);
     322            1 :                 }
     323              :             }
     324              :         }
     325            2 :     }
     326              : }
     327              : 
     328              : // SharedState wrapper.
     329              : #[derive(Clone)]
     330              : struct Registry {
     331              :     shared_state: Arc<RwLock<SharedState>>,
     332              :     timeline_chan_size: usize,
     333              : }
     334              : 
     335              : impl Registry {
     336              :     // Register new publisher in shared state.
     337            1 :     pub fn register_publisher(&self, remote_addr: SocketAddr) -> Publisher {
     338            1 :         let pub_id = self.shared_state.write().register_publisher();
     339            1 :         info!("publication started id={} addr={:?}", pub_id, remote_addr);
     340            1 :         Publisher {
     341            1 :             id: pub_id,
     342            1 :             registry: self.clone(),
     343            1 :             remote_addr,
     344            1 :         }
     345            1 :     }
     346              : 
     347            1 :     pub fn unregister_publisher(&self, publisher: &Publisher) {
     348            1 :         self.shared_state.write().unregister_publisher();
     349            1 :         info!(
     350            0 :             "publication ended id={} addr={:?}",
     351              :             publisher.id, publisher.remote_addr
     352              :         );
     353            1 :     }
     354              : 
     355              :     // Register new subscriber in shared state.
     356            2 :     pub fn register_subscriber(
     357            2 :         &self,
     358            2 :         sub_key: SubscriptionKey,
     359            2 :         remote_addr: SocketAddr,
     360            2 :     ) -> Subscriber {
     361            2 :         let (sub_id, sub_rx) = self
     362            2 :             .shared_state
     363            2 :             .write()
     364            2 :             .register_subscriber(sub_key, self.timeline_chan_size);
     365            2 :         info!(
     366            0 :             "subscription started id={}, key={:?}, addr={:?}",
     367              :             sub_id, sub_key, remote_addr
     368              :         );
     369            2 :         Subscriber {
     370            2 :             id: sub_id,
     371            2 :             key: sub_key,
     372            2 :             sub_rx,
     373            2 :             registry: self.clone(),
     374            2 :             remote_addr,
     375            2 :         }
     376            2 :     }
     377              : 
     378              :     // Unregister the subscriber
     379            2 :     pub fn unregister_subscriber(&self, subscriber: &Subscriber) {
     380            2 :         self.shared_state
     381            2 :             .write()
     382            2 :             .unregister_subscriber(subscriber.key);
     383            2 :         info!(
     384            0 :             "subscription ended id={}, key={:?}, addr={:?}",
     385              :             subscriber.id, subscriber.key, subscriber.remote_addr
     386              :         );
     387            2 :     }
     388              : 
     389              :     /// Send msg to relevant subscribers.
     390            2 :     pub fn send_msg(&self, msg: &Message) -> Result<(), Status> {
     391            2 :         PROCESSED_MESSAGES_TOTAL.inc();
     392            2 : 
     393            2 :         // send message to subscribers for everything
     394            2 :         let shared_state = self.shared_state.read();
     395            2 :         // Err means there is no subscribers, it is fine.
     396            2 :         shared_state.chan_to_all_subs.send(msg.clone()).ok();
     397              : 
     398              :         // send message to per timeline subscribers, if there is ttid
     399            2 :         let ttid = msg.tenant_timeline_id()?;
     400            2 :         if let Some(ttid) = ttid {
     401            2 :             if let Some(subs) = shared_state.chans_to_timeline_subs.get(&ttid) {
     402            1 :                 // Err can't happen here, as tx is destroyed only after removing
     403            1 :                 // from the map the last subscriber along with tx.
     404            1 :                 subs.chan
     405            1 :                     .send(msg.clone())
     406            1 :                     .expect("rx is still in the map with zero subscribers");
     407            1 :             }
     408            0 :         }
     409            2 :         Ok(())
     410            2 :     }
     411              : }
     412              : 
     413              : // Private subscriber state.
     414              : struct Subscriber {
     415              :     id: SubId,
     416              :     key: SubscriptionKey,
     417              :     // Subscriber receives messages from publishers here.
     418              :     sub_rx: broadcast::Receiver<Message>,
     419              :     // to unregister itself from shared state in Drop
     420              :     registry: Registry,
     421              :     // for logging
     422              :     remote_addr: SocketAddr,
     423              : }
     424              : 
     425              : impl Drop for Subscriber {
     426            2 :     fn drop(&mut self) {
     427            2 :         self.registry.unregister_subscriber(self);
     428            2 :     }
     429              : }
     430              : 
     431              : // Private publisher state
     432              : struct Publisher {
     433              :     id: PubId,
     434              :     registry: Registry,
     435              :     // for logging
     436              :     remote_addr: SocketAddr,
     437              : }
     438              : 
     439              : impl Publisher {
     440              :     /// Send msg to relevant subscribers.
     441            2 :     pub fn send_msg(&mut self, msg: &Message) -> Result<(), Status> {
     442            2 :         self.registry.send_msg(msg)
     443            2 :     }
     444              : }
     445              : 
     446              : impl Drop for Publisher {
     447            1 :     fn drop(&mut self) {
     448            1 :         self.registry.unregister_publisher(self);
     449            1 :     }
     450              : }
     451              : 
     452              : struct Broker {
     453              :     registry: Registry,
     454              : }
     455              : 
     456              : #[tonic::async_trait]
     457              : impl BrokerService for Broker {
     458            0 :     async fn publish_safekeeper_info(
     459            0 :         &self,
     460            0 :         request: Request<tonic::Streaming<SafekeeperTimelineInfo>>,
     461            0 :     ) -> Result<Response<()>, Status> {
     462            0 :         let remote_addr = request
     463            0 :             .remote_addr()
     464            0 :             .expect("TCPConnectInfo inserted by handler");
     465            0 :         let mut publisher = self.registry.register_publisher(remote_addr);
     466            0 : 
     467            0 :         let mut stream = request.into_inner();
     468              : 
     469              :         loop {
     470            0 :             match stream.next().await {
     471            0 :                 Some(Ok(msg)) => publisher.send_msg(&Message::SafekeeperTimelineInfo(msg))?,
     472            0 :                 Some(Err(e)) => return Err(e), // grpc error from the stream
     473            0 :                 None => break,                 // closed stream
     474            0 :             }
     475            0 :         }
     476            0 : 
     477            0 :         Ok(Response::new(()))
     478            0 :     }
     479              : 
     480              :     type SubscribeSafekeeperInfoStream =
     481              :         Pin<Box<dyn Stream<Item = Result<SafekeeperTimelineInfo, Status>> + Send + 'static>>;
     482              : 
     483            0 :     async fn subscribe_safekeeper_info(
     484            0 :         &self,
     485            0 :         request: Request<SubscribeSafekeeperInfoRequest>,
     486            0 :     ) -> Result<Response<Self::SubscribeSafekeeperInfoStream>, Status> {
     487            0 :         let remote_addr = request
     488            0 :             .remote_addr()
     489            0 :             .expect("TCPConnectInfo inserted by handler");
     490            0 :         let proto_key = request
     491            0 :             .into_inner()
     492            0 :             .subscription_key
     493            0 :             .ok_or_else(|| Status::new(Code::InvalidArgument, "missing subscription key"))?;
     494            0 :         let sub_key = SubscriptionKey::from_proto_subscription_key(proto_key)?;
     495            0 :         let mut subscriber = self.registry.register_subscriber(sub_key, remote_addr);
     496            0 : 
     497            0 :         // transform rx into stream with item = Result, as method result demands
     498            0 :         let output = async_stream::try_stream! {
     499            0 :             let mut warn_interval = time::interval(Duration::from_millis(1000));
     500            0 :             let mut missed_msgs: u64 = 0;
     501            0 :             loop {
     502            0 :                 match subscriber.sub_rx.recv().await {
     503            0 :                     Ok(info) => {
     504            0 :                         match info {
     505            0 :                             Message::SafekeeperTimelineInfo(info) => yield info,
     506            0 :                             _ => {},
     507            0 :                         }
     508            0 :                         BROADCASTED_MESSAGES_TOTAL.inc();
     509            0 :                     },
     510            0 :                     Err(RecvError::Lagged(skipped_msg)) => {
     511            0 :                         BROADCAST_DROPPED_MESSAGES_TOTAL.inc_by(skipped_msg);
     512            0 :                         missed_msgs += skipped_msg;
     513            0 :                         if (futures::poll!(Box::pin(warn_interval.tick()))).is_ready() {
     514            0 :                             warn!("subscription id={}, key={:?} addr={:?} dropped {} messages, channel is full",
     515            0 :                                 subscriber.id, subscriber.key, subscriber.remote_addr, missed_msgs);
     516            0 :                             missed_msgs = 0;
     517            0 :                         }
     518            0 :                     }
     519            0 :                     Err(RecvError::Closed) => {
     520            0 :                         // can't happen, we never drop the channel while there is a subscriber
     521            0 :                         Err(Status::new(Code::Internal, "channel unexpectantly closed"))?;
     522            0 :                     }
     523            0 :                 }
     524            0 :             }
     525            0 :         };
     526            0 : 
     527            0 :         Ok(Response::new(
     528            0 :             Box::pin(output) as Self::SubscribeSafekeeperInfoStream
     529            0 :         ))
     530            0 :     }
     531              : 
     532              :     type SubscribeByFilterStream =
     533              :         Pin<Box<dyn Stream<Item = Result<TypedMessage, Status>> + Send + 'static>>;
     534              : 
     535              :     /// Subscribe to all messages, limited by a filter.
     536            0 :     async fn subscribe_by_filter(
     537            0 :         &self,
     538            0 :         request: Request<SubscribeByFilterRequest>,
     539            0 :     ) -> std::result::Result<Response<Self::SubscribeByFilterStream>, Status> {
     540            0 :         let remote_addr = request
     541            0 :             .remote_addr()
     542            0 :             .expect("TCPConnectInfo inserted by handler");
     543            0 :         let proto_filter = request.into_inner();
     544            0 :         let ttid_filter = proto_filter.tenant_timeline_id.as_ref();
     545              : 
     546            0 :         let sub_key = SubscriptionKey::from_proto_filter_tenant_timeline_id(ttid_filter)?;
     547            0 :         let types_set = proto_filter
     548            0 :             .types
     549            0 :             .iter()
     550            0 :             .map(|t| t.r#type)
     551            0 :             .collect::<std::collections::HashSet<_>>();
     552            0 : 
     553            0 :         let mut subscriber = self.registry.register_subscriber(sub_key, remote_addr);
     554            0 : 
     555            0 :         // transform rx into stream with item = Result, as method result demands
     556            0 :         let output = async_stream::try_stream! {
     557            0 :             let mut warn_interval = time::interval(Duration::from_millis(1000));
     558            0 :             let mut missed_msgs: u64 = 0;
     559            0 :             loop {
     560            0 :                 match subscriber.sub_rx.recv().await {
     561            0 :                     Ok(msg) => {
     562            0 :                         let msg_type = msg.message_type() as i32;
     563            0 :                         if types_set.contains(&msg_type) {
     564            0 :                             yield msg.as_typed_message();
     565            0 :                             BROADCASTED_MESSAGES_TOTAL.inc();
     566            0 :                         }
     567            0 :                     },
     568            0 :                     Err(RecvError::Lagged(skipped_msg)) => {
     569            0 :                         BROADCAST_DROPPED_MESSAGES_TOTAL.inc_by(skipped_msg);
     570            0 :                         missed_msgs += skipped_msg;
     571            0 :                         if (futures::poll!(Box::pin(warn_interval.tick()))).is_ready() {
     572            0 :                             warn!("subscription id={}, key={:?} addr={:?} dropped {} messages, channel is full",
     573            0 :                                 subscriber.id, subscriber.key, subscriber.remote_addr, missed_msgs);
     574            0 :                             missed_msgs = 0;
     575            0 :                         }
     576            0 :                     }
     577            0 :                     Err(RecvError::Closed) => {
     578            0 :                         // can't happen, we never drop the channel while there is a subscriber
     579            0 :                         Err(Status::new(Code::Internal, "channel unexpectantly closed"))?;
     580            0 :                     }
     581            0 :                 }
     582            0 :             }
     583            0 :         };
     584            0 : 
     585            0 :         Ok(Response::new(
     586            0 :             Box::pin(output) as Self::SubscribeByFilterStream
     587            0 :         ))
     588            0 :     }
     589              : 
     590              :     /// Publish one message.
     591            0 :     async fn publish_one(
     592            0 :         &self,
     593            0 :         request: Request<TypedMessage>,
     594            0 :     ) -> std::result::Result<Response<()>, Status> {
     595            0 :         let msg = Message::from(request.into_inner())?;
     596            0 :         PUBLISHED_ONEOFF_MESSAGES_TOTAL.inc();
     597            0 :         self.registry.send_msg(&msg)?;
     598            0 :         Ok(Response::new(()))
     599            0 :     }
     600              : }
     601              : 
     602              : // We serve only metrics and healthcheck through http1.
     603            0 : async fn http1_handler(
     604            0 :     req: hyper::Request<Incoming>,
     605            0 : ) -> Result<hyper::Response<BoxBody>, Infallible> {
     606            0 :     let resp = match (req.method(), req.uri().path()) {
     607            0 :         (&Method::GET, "/metrics") => {
     608            0 :             let mut buffer = vec![];
     609            0 :             let metrics = metrics::gather();
     610            0 :             let encoder = TextEncoder::new();
     611            0 :             encoder.encode(&metrics, &mut buffer).unwrap();
     612            0 : 
     613            0 :             hyper::Response::builder()
     614            0 :                 .status(StatusCode::OK)
     615            0 :                 .header(CONTENT_TYPE, encoder.format_type())
     616            0 :                 .body(body::boxed(Full::new(bytes::Bytes::from(buffer))))
     617            0 :                 .unwrap()
     618              :         }
     619            0 :         (&Method::GET, "/status") => hyper::Response::builder()
     620            0 :             .status(StatusCode::OK)
     621            0 :             .body(empty_body())
     622            0 :             .unwrap(),
     623            0 :         _ => hyper::Response::builder()
     624            0 :             .status(StatusCode::NOT_FOUND)
     625            0 :             .body(empty_body())
     626            0 :             .unwrap(),
     627              :     };
     628            0 :     Ok(resp)
     629            0 : }
     630              : 
     631              : #[tokio::main]
     632            0 : async fn main() -> Result<(), Box<dyn std::error::Error>> {
     633            0 :     let args = Args::parse();
     634            0 : 
     635            0 :     // important to keep the order of:
     636            0 :     // 1. init logging
     637            0 :     // 2. tracing panic hook
     638            0 :     // 3. sentry
     639            0 :     logging::init(
     640            0 :         LogFormat::from_config(&args.log_format)?,
     641            0 :         logging::TracingErrorLayerEnablement::Disabled,
     642            0 :         logging::Output::Stdout,
     643            0 :     )?;
     644            0 :     logging::replace_panic_hook_with_tracing_panic_hook().forget();
     645            0 :     // initialize sentry if SENTRY_DSN is provided
     646            0 :     let _sentry_guard = init_sentry(Some(GIT_VERSION.into()), &[]);
     647            0 :     info!("version: {GIT_VERSION} build_tag: {BUILD_TAG}");
     648            0 :     metrics::set_build_info_metric(GIT_VERSION, BUILD_TAG);
     649            0 : 
     650            0 :     // On any shutdown signal, log receival and exit.
     651            0 :     std::thread::spawn(move || {
     652            0 :         ShutdownSignals::handle(|signal| {
     653            0 :             info!("received {}, terminating", signal.name());
     654            0 :             std::process::exit(0);
     655            0 :         })
     656            0 :     });
     657            0 : 
     658            0 :     let registry = Registry {
     659            0 :         shared_state: Arc::new(RwLock::new(SharedState::new(args.all_keys_chan_size))),
     660            0 :         timeline_chan_size: args.timeline_chan_size,
     661            0 :     };
     662            0 :     let storage_broker_impl = Broker {
     663            0 :         registry: registry.clone(),
     664            0 :     };
     665            0 :     let storage_broker_server = BrokerServiceServer::new(storage_broker_impl);
     666            0 : 
     667            0 :     // grpc is served along with http1 for metrics on a single port, hence we
     668            0 :     // don't use tonic's Server.
     669            0 :     let tcp_listener = TcpListener::bind(&args.listen_addr).await?;
     670            0 :     info!("listening on {}", &args.listen_addr);
     671            0 :     loop {
     672            0 :         let (stream, addr) = match tcp_listener.accept().await {
     673            0 :             Ok(v) => v,
     674            0 :             Err(e) => {
     675            0 :                 info!("couldn't accept connection: {e}");
     676            0 :                 continue;
     677            0 :             }
     678            0 :         };
     679            0 : 
     680            0 :         let mut builder = hyper_util::server::conn::auto::Builder::new(TokioExecutor::new());
     681            0 :         builder.http1().timer(TokioTimer::new());
     682            0 :         builder
     683            0 :             .http2()
     684            0 :             .timer(TokioTimer::new())
     685            0 :             .keep_alive_interval(Some(args.http2_keepalive_interval))
     686            0 :             // This matches the tonic server default. It allows us to support production-like workloads.
     687            0 :             .max_concurrent_streams(None);
     688            0 : 
     689            0 :         let storage_broker_server_cloned = storage_broker_server.clone();
     690            0 :         let connect_info = stream.connect_info();
     691            0 :         let service_fn_ = async move {
     692            0 :             service_fn(move |mut req| {
     693            0 :                 // That's what tonic's MakeSvc.call does to pass conninfo to
     694            0 :                 // the request handler (and where its request.remote_addr()
     695            0 :                 // expects it to find).
     696            0 :                 req.extensions_mut().insert(connect_info.clone());
     697            0 : 
     698            0 :                 // Technically this second clone is not needed, but consume
     699            0 :                 // by async block is apparently unavoidable. BTW, error
     700            0 :                 // message is enigmatic, see
     701            0 :                 // https://github.com/rust-lang/rust/issues/68119
     702            0 :                 //
     703            0 :                 // We could get away without async block at all, but then we
     704            0 :                 // need to resort to futures::Either to merge the result,
     705            0 :                 // which doesn't caress an eye as well.
     706            0 :                 let mut storage_broker_server_svc = storage_broker_server_cloned.clone();
     707            0 :                 async move {
     708            0 :                     if req.headers().get("content-type").map(|x| x.as_bytes())
     709            0 :                         == Some(b"application/grpc")
     710            0 :                     {
     711            0 :                         let res_resp = storage_broker_server_svc.call(req).await;
     712            0 :                         // Grpc and http1 handlers have slightly different
     713            0 :                         // Response types: it is UnsyncBoxBody for the
     714            0 :                         // former one (not sure why) and plain hyper::Body
     715            0 :                         // for the latter. Both implement HttpBody though,
     716            0 :                         // and `Either` is used to merge them.
     717            0 :                         res_resp.map(|resp| resp.map(http_body_util::Either::Left))
     718            0 :                     } else {
     719            0 :                         let res_resp = http1_handler(req).await;
     720            0 :                         res_resp.map(|resp| resp.map(http_body_util::Either::Right))
     721            0 :                     }
     722            0 :                 }
     723            0 :             })
     724            0 :         }
     725            0 :         .await;
     726            0 : 
     727            0 :         tokio::task::spawn(async move {
     728            0 :             let res = builder
     729            0 :                 .serve_connection(TokioIo::new(stream), service_fn_)
     730            0 :                 .await;
     731            0 : 
     732            0 :             if let Err(e) = res {
     733            0 :                 info!("error serving connection from {addr}: {e}");
     734            0 :             }
     735            0 :         });
     736            0 :     }
     737            0 : }
     738              : 
     739              : #[cfg(test)]
     740              : mod tests {
     741              :     use super::*;
     742              :     use storage_broker::proto::TenantTimelineId as ProtoTenantTimelineId;
     743              :     use tokio::sync::broadcast::error::TryRecvError;
     744              :     use utils::id::{TenantId, TimelineId};
     745              : 
     746            2 :     fn msg(timeline_id: Vec<u8>) -> Message {
     747            2 :         Message::SafekeeperTimelineInfo(SafekeeperTimelineInfo {
     748            2 :             safekeeper_id: 1,
     749            2 :             tenant_timeline_id: Some(ProtoTenantTimelineId {
     750            2 :                 tenant_id: vec![0x00; 16],
     751            2 :                 timeline_id,
     752            2 :             }),
     753            2 :             term: 0,
     754            2 :             last_log_term: 0,
     755            2 :             flush_lsn: 1,
     756            2 :             commit_lsn: 2,
     757            2 :             backup_lsn: 3,
     758            2 :             remote_consistent_lsn: 4,
     759            2 :             peer_horizon_lsn: 5,
     760            2 :             safekeeper_connstr: "neon-1-sk-1.local:7676".to_owned(),
     761            2 :             http_connstr: "neon-1-sk-1.local:7677".to_owned(),
     762            2 :             local_start_lsn: 0,
     763            2 :             availability_zone: None,
     764            2 :             standby_horizon: 0,
     765            2 :         })
     766            2 :     }
     767              : 
     768            3 :     fn tli_from_u64(i: u64) -> Vec<u8> {
     769            3 :         let mut timeline_id = vec![0xFF; 8];
     770            3 :         timeline_id.extend_from_slice(&i.to_be_bytes());
     771            3 :         timeline_id
     772            3 :     }
     773              : 
     774            3 :     fn mock_addr() -> SocketAddr {
     775            3 :         "127.0.0.1:8080".parse().unwrap()
     776            3 :     }
     777              : 
     778              :     #[tokio::test]
     779            1 :     async fn test_registry() {
     780            1 :         let registry = Registry {
     781            1 :             shared_state: Arc::new(RwLock::new(SharedState::new(16))),
     782            1 :             timeline_chan_size: 16,
     783            1 :         };
     784            1 : 
     785            1 :         // subscribe to timeline 2
     786            1 :         let ttid_2 = TenantTimelineId {
     787            1 :             tenant_id: TenantId::from_slice(&[0x00; 16]).unwrap(),
     788            1 :             timeline_id: TimelineId::from_slice(&tli_from_u64(2)).unwrap(),
     789            1 :         };
     790            1 :         let sub_key_2 = SubscriptionKey::Timeline(ttid_2);
     791            1 :         let mut subscriber_2 = registry.register_subscriber(sub_key_2, mock_addr());
     792            1 :         let mut subscriber_all = registry.register_subscriber(SubscriptionKey::All, mock_addr());
     793            1 : 
     794            1 :         // send two messages with different keys
     795            1 :         let msg_1 = msg(tli_from_u64(1));
     796            1 :         let msg_2 = msg(tli_from_u64(2));
     797            1 :         let mut publisher = registry.register_publisher(mock_addr());
     798            1 :         publisher.send_msg(&msg_1).expect("failed to send msg");
     799            1 :         publisher.send_msg(&msg_2).expect("failed to send msg");
     800            1 : 
     801            1 :         // msg with key 2 should arrive to subscriber_2
     802            1 :         assert_eq!(subscriber_2.sub_rx.try_recv().unwrap(), msg_2);
     803            1 : 
     804            1 :         // but nothing more
     805            1 :         assert_eq!(
     806            1 :             subscriber_2.sub_rx.try_recv().unwrap_err(),
     807            1 :             TryRecvError::Empty
     808            1 :         );
     809            1 : 
     810            1 :         // subscriber_all should receive both messages
     811            1 :         assert_eq!(subscriber_all.sub_rx.try_recv().unwrap(), msg_1);
     812            1 :         assert_eq!(subscriber_all.sub_rx.try_recv().unwrap(), msg_2);
     813            1 :         assert_eq!(
     814            1 :             subscriber_all.sub_rx.try_recv().unwrap_err(),
     815            1 :             TryRecvError::Empty
     816            1 :         );
     817            1 :     }
     818              : }
        

Generated by: LCOV version 2.1-beta