common_meta/heartbeat/
mailbox.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 std::sync::Arc;
16
17use tokio::sync::mpsc::Sender;
18
19use crate::error::{self, Result};
20use crate::instruction::{Instruction, InstructionReply};
21
22pub type IncomingMessage = (MessageMeta, Instruction);
23pub type OutgoingMessage = (MessageMeta, InstructionReply);
24
25#[derive(Debug, PartialEq, Eq, Clone)]
26pub struct MessageMeta {
27    pub id: u64,
28    pub subject: String,
29    pub to: String,
30    pub from: String,
31}
32
33impl MessageMeta {
34    #[cfg(any(test, feature = "testing"))]
35    pub fn new_test(id: u64, subject: &str, to: &str, from: &str) -> Self {
36        MessageMeta {
37            id,
38            subject: subject.to_string(),
39            to: to.to_string(),
40            from: from.to_string(),
41        }
42    }
43}
44
45pub struct HeartbeatMailbox {
46    sender: Sender<OutgoingMessage>,
47}
48
49impl HeartbeatMailbox {
50    pub fn new(sender: Sender<OutgoingMessage>) -> Self {
51        Self { sender }
52    }
53
54    pub async fn send(&self, message: OutgoingMessage) -> Result<()> {
55        self.sender.send(message).await.map_err(|e| {
56            error::SendMessageSnafu {
57                err_msg: e.to_string(),
58            }
59            .build()
60        })
61    }
62}
63
64pub type MailboxRef = Arc<HeartbeatMailbox>;