testcontainers_modules/pulsar/
mod.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
use std::{borrow::Cow, collections::BTreeMap};

use testcontainers::{
    core::{CmdWaitFor, ContainerPort, ContainerState, ExecCommand, Mount, WaitFor},
    Image, TestcontainersError,
};

const NAME: &str = "apachepulsar/pulsar";
const TAG: &str = "2.10.6";

const PULSAR_PORT: ContainerPort = ContainerPort::Tcp(6650);
const ADMIN_PORT: ContainerPort = ContainerPort::Tcp(8080);

/// Module to work with [`Apache Pulsar`] inside of tests.
/// **Requires protoc to be installed, otherwise will not build.**
///
/// This module is based on the official [`Apache Pulsar docker image`].
///
/// # Example
/// ```
/// use testcontainers_modules::{pulsar, testcontainers::runners::SyncRunner};
///
/// let pulsar = pulsar::Pulsar::default().start().unwrap();
/// let http_port = pulsar.get_host_port_ipv4(6650).unwrap();
///
/// // do something with the running pulsar instance..
/// ```
///
/// [`Apache Pulsar`]: https://github.com/apache/pulsar
/// [`Apache Pulsar docker image`]: https://hub.docker.com/r/apachepulsar/pulsar/
#[derive(Debug, Clone)]
pub struct Pulsar {
    data_mount: Mount,
    env: BTreeMap<String, String>,
    admin_commands: Vec<Vec<String>>,
}

impl Default for Pulsar {
    /**
     * Creates new standalone pulsar container, with `/pulsar/data` as a temporary volume
     */
    fn default() -> Self {
        Self {
            data_mount: Mount::tmpfs_mount("/pulsar/data"),
            env: BTreeMap::new(),
            admin_commands: vec![],
        }
    }
}

impl Pulsar {
    /// Add configuration parameter to Pulsar `conf/standalone.conf` through setting environment variable.
    ///
    /// Container will rewrite `conf/standalone.conf` file using these variables during startup
    /// with help of `bin/apply-config-from-env.py` script
    pub fn with_config_env(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.env
            .insert(format!("PULSAR_PREFIX_{}", name.into()), value.into());
        self
    }

    /// Runs admin command after container start
    pub fn with_admin_command(
        mut self,
        command: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        let mut vec: Vec<String> = command.into_iter().map(Into::into).collect();
        vec.insert(0, "bin/pulsar-admin".to_string());
        self.admin_commands.push(vec);
        self
    }

    /// Creates tenant after container start
    pub fn with_tenant(self, tenant: impl Into<String>) -> Self {
        let tenant = tenant.into();
        self.with_admin_command(["tenants", "create", &tenant])
    }

    /// Creates namespace after container start
    pub fn with_namespace(self, namespace: impl Into<String>) -> Self {
        let namespace = namespace.into();
        self.with_admin_command(["namespaces", "create", &namespace])
    }

    /// Creates topic after container start
    pub fn with_topic(self, topic: impl Into<String>) -> Self {
        let topic = topic.into();
        self.with_admin_command(["topics", "create", &topic])
    }
}

impl Image for Pulsar {
    fn name(&self) -> &str {
        NAME
    }

    fn tag(&self) -> &str {
        TAG
    }

    fn ready_conditions(&self) -> Vec<WaitFor> {
        vec![
            WaitFor::message_on_stdout("HTTP Service started at"),
            WaitFor::message_on_stdout("messaging service is ready"),
        ]
    }

    fn mounts(&self) -> impl IntoIterator<Item = &Mount> {
        [&self.data_mount]
    }

    fn env_vars(
        &self,
    ) -> impl IntoIterator<Item = (impl Into<Cow<'_, str>>, impl Into<Cow<'_, str>>)> {
        &self.env
    }

    fn cmd(&self) -> impl IntoIterator<Item = impl Into<Cow<'_, str>>> {
        [
            "sh",
            "-c",
            "bin/apply-config-from-env.py conf/standalone.conf && bin/pulsar standalone",
        ]
    }

    fn exec_after_start(
        &self,
        _cs: ContainerState,
    ) -> Result<Vec<ExecCommand>, TestcontainersError> {
        Ok(self
            .admin_commands
            .iter()
            .map(|cmd| ExecCommand::new(cmd).with_cmd_ready_condition(CmdWaitFor::exit_code(0)))
            .collect())
    }

    fn expose_ports(&self) -> &[ContainerPort] {
        &[PULSAR_PORT, ADMIN_PORT]
    }
}

#[cfg(test)]
mod tests {
    use futures::StreamExt;
    use pulsar::{
        producer::Message, Consumer, DeserializeMessage, Error, Payload, SerializeMessage,
        TokioExecutor,
    };
    use serde::{Deserialize, Serialize};

    use super::*;
    use crate::testcontainers::runners::AsyncRunner;

    #[derive(Serialize, Deserialize)]
    struct TestData {
        data: String,
    }

    impl DeserializeMessage for TestData {
        type Output = Result<TestData, serde_json::Error>;

        fn deserialize_message(payload: &Payload) -> Self::Output {
            serde_json::from_slice(&payload.data)
        }
    }

    impl SerializeMessage for TestData {
        fn serialize_message(input: Self) -> Result<Message, Error> {
            Ok(Message {
                payload: serde_json::to_vec(&input).map_err(|e| Error::Custom(e.to_string()))?,
                ..Default::default()
            })
        }
    }

    #[tokio::test]
    async fn pulsar_subscribe_and_publish() -> Result<(), Box<dyn std::error::Error + 'static>> {
        let topic = "persistent://test/test-ns/test-topic";

        let pulsar = Pulsar::default()
            .with_tenant("test")
            .with_namespace("test/test-ns")
            .with_topic(topic)
            .start()
            .await
            .unwrap();

        let endpoint = format!(
            "pulsar://0.0.0.0:{}",
            pulsar.get_host_port_ipv4(6650).await?
        );
        let client = pulsar::Pulsar::builder(endpoint, TokioExecutor)
            .build()
            .await?;

        let mut consumer: Consumer<TestData, _> =
            client.consumer().with_topic(topic).build().await?;

        let mut producer = client.producer().with_topic(topic).build().await?;

        producer
            .send_non_blocking(TestData {
                data: "test".to_string(),
            })
            .await?
            .await?;

        let data = consumer.next().await.unwrap()?.deserialize()?;
        assert_eq!("test", data.data);

        Ok(())
    }

    #[tokio::test]
    async fn pulsar_config() -> Result<(), Box<dyn std::error::Error + 'static>> {
        let topic = "persistent://test/test-ns/test-topic";

        let pulsar = Pulsar::default()
            .with_tenant("test")
            .with_namespace("test/test-ns")
            .with_config_env("allowAutoTopicCreation", "false")
            .start()
            .await
            .unwrap();

        let endpoint = format!(
            "pulsar://0.0.0.0:{}",
            pulsar.get_host_port_ipv4(6650).await?
        );
        let client = pulsar::Pulsar::builder(endpoint, TokioExecutor)
            .build()
            .await?;

        let producer = client.producer().with_topic(topic).build().await;

        match producer {
            Ok(_) => panic!("Producer should return error"),
            Err(e) => assert_eq!("Connection error: Server error (Some(TopicNotFound)): Topic not found persistent://test/test-ns/test-topic", e.to_string()),
        }

        Ok(())
    }
}