Skip to main content

risingwave_common_service/
observer_manager.rs

1// Copyright 2022 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::time::Duration;
16
17use risingwave_pb::meta::subscribe_response::Info;
18use risingwave_pb::meta::{SubscribeResponse, SubscribeType};
19use risingwave_rpc_client::MetaClient;
20use risingwave_rpc_client::error::RpcError;
21use thiserror_ext::AsReport;
22use tokio::task::JoinHandle;
23use tonic::{Status, Streaming};
24
25/// `ObserverManager` is used to update data based on notification from meta.
26/// Call `start` to spawn a new asynchronous task
27/// We can write the notification logic by implementing `ObserverNodeImpl`.
28pub struct ObserverManager<T: NotificationClient, S: ObserverState> {
29    rx: T::Channel,
30    client: T,
31    observer_states: S,
32}
33
34pub trait ObserverState: Send + 'static {
35    fn subscribe_type() -> SubscribeType;
36    /// modify data after receiving notification from meta
37    fn handle_notification(&mut self, resp: SubscribeResponse);
38
39    /// Initialize data from the meta. It will be called at start or resubscribe
40    fn handle_initialization_notification(&mut self, resp: SubscribeResponse);
41}
42
43impl<S: ObserverState> ObserverManager<RpcNotificationClient, S> {
44    pub async fn new_with_meta_client(meta_client: MetaClient, observer_states: S) -> Self {
45        let client = RpcNotificationClient { meta_client };
46        Self::new(client, observer_states).await
47    }
48}
49
50/// Error type for [`ObserverManager`].
51#[derive(thiserror::Error, Debug)]
52pub enum ObserverError {
53    #[error("notification channel closed")]
54    ChannelClosed,
55
56    #[error(transparent)]
57    Rpc(
58        #[from]
59        #[backtrace]
60        RpcError,
61    ),
62}
63
64impl From<tonic::Status> for ObserverError {
65    fn from(status: tonic::Status) -> Self {
66        Self::Rpc(RpcError::from_meta_status(status))
67    }
68}
69
70impl<T, S> ObserverManager<T, S>
71where
72    T: NotificationClient,
73    S: ObserverState,
74{
75    pub async fn new(client: T, observer_states: S) -> Self {
76        let rx = client.subscribe(S::subscribe_type()).await.unwrap();
77        Self {
78            rx,
79            client,
80            observer_states,
81        }
82    }
83
84    /// `wait_init_notification` is used to wait for the initial notification from meta
85    /// and process the buffered notifications before the initial notification if needed.
86    async fn wait_init_notification(&mut self) -> Result<(), ObserverError> {
87        let mut notification_vec = Vec::new();
88        let init_notification = loop {
89            // notification before init notification must be received successfully.
90            match self.rx.message().await? {
91                Some(notification) => {
92                    if !matches!(notification.info.as_ref().unwrap(), &Info::Snapshot(_)) {
93                        notification_vec.push(notification);
94                    } else {
95                        break notification;
96                    }
97                }
98                None => return Err(ObserverError::ChannelClosed),
99            }
100        };
101
102        let Info::Snapshot(info) = init_notification.info.as_ref().unwrap() else {
103            unreachable!();
104        };
105
106        notification_vec.retain_mut(|notification| match notification.info.as_ref().unwrap() {
107            Info::Database(_)
108            | Info::Schema(_)
109            | Info::ObjectGroup(_)
110            | Info::User(_)
111            | Info::Connection(_)
112            | Info::Secret(_)
113            | Info::Function(_) => {
114                notification.version > info.version.as_ref().unwrap().catalog_version
115            }
116            Info::Node(_) => {
117                notification.version > info.version.as_ref().unwrap().worker_node_version
118            }
119            Info::HummockVersionDeltas(version_delta) => {
120                version_delta.version_deltas[0].id > info.hummock_version.as_ref().unwrap().id
121            }
122            Info::MetaBackupManifestId(_) => true,
123            Info::SystemParams(_) | Info::SessionParam(_) => true,
124            // It carries the whole limit table, so applying it after the snapshot in queue order
125            // ends at the latest limits.
126            Info::HummockWriteLimits(_) => true,
127            Info::Snapshot(_) => unreachable!(),
128            Info::HummockStats(_) => true,
129            Info::Recovery(_) => true,
130            Info::ClusterResource(_) => true,
131            Info::StreamingWorkerSlotMapping(_) => {
132                notification.version
133                    > info
134                        .version
135                        .as_ref()
136                        .unwrap()
137                        .streaming_worker_slot_mapping_version
138            }
139            Info::ServingWorkerSlotMappings(_) => true,
140            Info::TableRefillRuntimeConfig(_) => {
141                notification.version
142                    > info
143                        .table_refill_runtime_config
144                        .as_ref()
145                        .map(|config| config.version)
146                        .unwrap_or_default()
147            }
148        });
149
150        self.observer_states
151            .handle_initialization_notification(init_notification);
152
153        for notification in notification_vec {
154            self.observer_states.handle_notification(notification);
155        }
156
157        Ok(())
158    }
159
160    /// `start` is used to spawn a new asynchronous task which receives meta's notification and
161    /// call the `handle_initialization_notification` and `handle_notification` to update node data.
162    pub async fn start(mut self) -> JoinHandle<()> {
163        if let Err(err) = self.wait_init_notification().await {
164            tracing::warn!(error = %err.as_report(), "Receives meta's notification err");
165            self.re_subscribe().await;
166        }
167
168        tokio::spawn(async move {
169            loop {
170                match self.rx.message().await {
171                    Ok(resp) => {
172                        if resp.is_none() {
173                            tracing::warn!("Stream of notification terminated.");
174                            self.re_subscribe().await;
175                            continue;
176                        }
177                        self.observer_states.handle_notification(resp.unwrap());
178                    }
179                    Err(err) => {
180                        tracing::warn!(error = %err.as_report(), "Receives meta's notification err");
181                        self.re_subscribe().await;
182                    }
183                }
184            }
185        })
186    }
187
188    /// `re_subscribe` is used to re-subscribe to the meta's notification.
189    async fn re_subscribe(&mut self) {
190        loop {
191            match self.client.subscribe(S::subscribe_type()).await {
192                Ok(rx) => {
193                    tracing::debug!("re-subscribe success");
194                    self.rx = rx;
195                    match self.wait_init_notification().await {
196                        Err(err) => {
197                            tracing::warn!(error = %err.as_report(), "Receives meta's notification err");
198                            tokio::time::sleep(RE_SUBSCRIBE_RETRY_INTERVAL).await;
199                            continue;
200                        }
201                        _ => {
202                            break;
203                        }
204                    }
205                }
206                Err(_) => {
207                    tokio::time::sleep(RE_SUBSCRIBE_RETRY_INTERVAL).await;
208                }
209            }
210        }
211    }
212}
213
214const RE_SUBSCRIBE_RETRY_INTERVAL: Duration = Duration::from_millis(100);
215
216#[async_trait::async_trait]
217pub trait Channel: Send + 'static {
218    type Item;
219    async fn message(&mut self) -> std::result::Result<Option<Self::Item>, Status>;
220}
221
222#[async_trait::async_trait]
223impl<T: Send + 'static> Channel for Streaming<T> {
224    type Item = T;
225
226    async fn message(&mut self) -> std::result::Result<Option<T>, Status> {
227        self.message().await
228    }
229}
230
231#[async_trait::async_trait]
232pub trait NotificationClient: Send + Sync + 'static {
233    type Channel: Channel<Item = SubscribeResponse>;
234    async fn subscribe(
235        &self,
236        subscribe_type: SubscribeType,
237    ) -> Result<Self::Channel, ObserverError>;
238}
239
240pub struct RpcNotificationClient {
241    meta_client: MetaClient,
242}
243
244impl RpcNotificationClient {
245    pub fn new(meta_client: MetaClient) -> Self {
246        Self { meta_client }
247    }
248}
249
250#[async_trait::async_trait]
251impl NotificationClient for RpcNotificationClient {
252    type Channel = Streaming<SubscribeResponse>;
253
254    async fn subscribe(
255        &self,
256        subscribe_type: SubscribeType,
257    ) -> Result<Self::Channel, ObserverError> {
258        self.meta_client
259            .subscribe(subscribe_type)
260            .await
261            .map_err(Into::into)
262    }
263}
264
265#[cfg(test)]
266mod tests {
267    use std::collections::VecDeque;
268
269    use risingwave_pb::meta::meta_snapshot::SnapshotVersion;
270    use risingwave_pb::meta::subscribe_response::Info;
271    use risingwave_pb::meta::{
272        MetaSnapshot, SubscribeResponse, SubscribeType, TableRefillRuntimeConfig,
273    };
274
275    use super::*;
276
277    struct TestChannel {
278        messages: VecDeque<SubscribeResponse>,
279    }
280
281    #[async_trait::async_trait]
282    impl Channel for TestChannel {
283        type Item = SubscribeResponse;
284
285        async fn message(&mut self) -> std::result::Result<Option<Self::Item>, Status> {
286            Ok(self.messages.pop_front())
287        }
288    }
289
290    struct TestClient;
291
292    #[async_trait::async_trait]
293    impl NotificationClient for TestClient {
294        type Channel = TestChannel;
295
296        async fn subscribe(
297            &self,
298            _subscribe_type: SubscribeType,
299        ) -> Result<Self::Channel, ObserverError> {
300            Ok(TestChannel {
301                messages: VecDeque::new(),
302            })
303        }
304    }
305
306    #[derive(Default)]
307    struct TestObserverState {
308        initialized: bool,
309        table_refill_runtime_config_versions: Vec<u64>,
310        database_notifications: usize,
311        write_limits_versions: Vec<u64>,
312    }
313
314    impl ObserverState for TestObserverState {
315        fn subscribe_type() -> SubscribeType {
316            SubscribeType::Hummock
317        }
318
319        fn handle_notification(&mut self, resp: SubscribeResponse) {
320            match resp.info.unwrap() {
321                Info::TableRefillRuntimeConfig(_) => {
322                    self.table_refill_runtime_config_versions.push(resp.version)
323                }
324                Info::Database(_) => self.database_notifications += 1,
325                Info::HummockWriteLimits(_) => {
326                    assert!(self.initialized);
327                    self.write_limits_versions.push(resp.version);
328                }
329                info => panic!("unexpected notification: {info:?}"),
330            }
331        }
332
333        fn handle_initialization_notification(&mut self, resp: SubscribeResponse) {
334            assert!(matches!(resp.info, Some(Info::Snapshot(_))));
335            self.initialized = true;
336        }
337    }
338
339    fn notification(version: u64, info: Info) -> SubscribeResponse {
340        SubscribeResponse {
341            info: Some(info),
342            version,
343            ..Default::default()
344        }
345    }
346
347    #[tokio::test]
348    async fn test_filter_stale_table_refill_runtime_config_before_snapshot() {
349        let snapshot = SubscribeResponse {
350            info: Some(Info::Snapshot(MetaSnapshot {
351                version: Some(SnapshotVersion {
352                    catalog_version: 1,
353                    worker_node_version: 1,
354                    streaming_worker_slot_mapping_version: 1,
355                }),
356                table_refill_runtime_config: Some(TableRefillRuntimeConfig {
357                    version: 10,
358                    ..Default::default()
359                }),
360                ..Default::default()
361            })),
362            ..Default::default()
363        };
364        let rx = TestChannel {
365            messages: VecDeque::from([
366                notification(
367                    9,
368                    Info::TableRefillRuntimeConfig(TableRefillRuntimeConfig {
369                        version: 9,
370                        ..Default::default()
371                    }),
372                ),
373                notification(
374                    11,
375                    Info::TableRefillRuntimeConfig(TableRefillRuntimeConfig {
376                        version: 11,
377                        ..Default::default()
378                    }),
379                ),
380                notification(1, Info::Database(Default::default())),
381                snapshot,
382            ]),
383        };
384        let mut observer_manager = ObserverManager {
385            rx,
386            client: TestClient,
387            observer_states: TestObserverState::default(),
388        };
389
390        observer_manager.wait_init_notification().await.unwrap();
391
392        assert!(observer_manager.observer_states.initialized);
393        assert_eq!(
394            observer_manager
395                .observer_states
396                .table_refill_runtime_config_versions,
397            vec![11]
398        );
399        assert_eq!(observer_manager.observer_states.database_notifications, 0);
400    }
401
402    #[tokio::test]
403    async fn test_keep_write_limits_before_snapshot() {
404        let rx = TestChannel {
405            messages: VecDeque::from([
406                notification(1, Info::HummockWriteLimits(Default::default())),
407                notification(2, Info::HummockWriteLimits(Default::default())),
408                notification(0, Info::Snapshot(Default::default())),
409            ]),
410        };
411        let mut observer_manager = ObserverManager {
412            rx,
413            client: TestClient,
414            observer_states: TestObserverState::default(),
415        };
416
417        observer_manager.wait_init_notification().await.unwrap();
418
419        assert_eq!(
420            observer_manager.observer_states.write_limits_versions,
421            vec![1, 2]
422        );
423    }
424}