meta_srv/handler/
check_leader_handler.rs

1// Copyright 2023 Greptime Team
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 api::v1::meta::{Error, HeartbeatRequest, Role};
16use common_telemetry::warn;
17
18use crate::error::Result;
19use crate::handler::{HandleControl, HeartbeatAccumulator, HeartbeatHandler};
20use crate::metasrv::Context;
21
22pub struct CheckLeaderHandler;
23
24#[async_trait::async_trait]
25impl HeartbeatHandler for CheckLeaderHandler {
26    fn is_acceptable(&self, _role: Role) -> bool {
27        true
28    }
29
30    async fn handle(
31        &self,
32        req: &HeartbeatRequest,
33        ctx: &mut Context,
34        acc: &mut HeartbeatAccumulator,
35    ) -> Result<HandleControl> {
36        let Some(election) = &ctx.election else {
37            return Ok(HandleControl::Continue);
38        };
39
40        if election.is_leader() {
41            return Ok(HandleControl::Continue);
42        }
43
44        warn!(
45            "A heartbeat was received {:?}, however, since the current node is not the leader,\
46            this heartbeat will be disregarded.",
47            req.header
48        );
49
50        if let Some(header) = &mut acc.header {
51            header.error = Some(Error::is_not_leader());
52        }
53
54        return Ok(HandleControl::Done);
55    }
56}