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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
use crate::{
    schema,
    sinks::{
        prelude::*,
        pulsar::sink::{healthcheck, PulsarSink},
    },
};
use futures_util::FutureExt;
use pulsar::{
    authentication::oauth2::{OAuth2Authentication, OAuth2Params},
    compression,
    message::proto,
    Authentication, ConnectionRetryOptions, Error as PulsarError, ProducerOptions, Pulsar,
    TokioExecutor,
};
use pulsar::{error::AuthenticationError, OperationRetryOptions};
use snafu::ResultExt;
use std::time::Duration;
use vector_lib::codecs::{encoding::SerializerConfig, TextSerializerConfig};
use vector_lib::config::DataType;
use vector_lib::lookup::lookup_v2::OptionalTargetPath;
use vector_lib::sensitive_string::SensitiveString;
use vrl::value::Kind;

/// Configuration for the `pulsar` sink.
#[configurable_component(sink("pulsar", "Publish observability events to Apache Pulsar topics."))]
#[derive(Clone, Debug)]
pub struct PulsarSinkConfig {
    /// The endpoint to which the Pulsar client should connect to.
    ///
    /// The endpoint should specify the pulsar protocol and port.
    #[serde(alias = "address")]
    #[configurable(metadata(docs::examples = "pulsar://127.0.0.1:6650"))]
    pub(crate) endpoint: String,

    /// The Pulsar topic name to write events to.
    #[configurable(metadata(docs::examples = "topic-1234"))]
    pub(crate) topic: Template,

    /// The name of the producer. If not specified, the default name assigned by Pulsar is used.
    #[configurable(metadata(docs::examples = "producer-name"))]
    pub(crate) producer_name: Option<String>,

    /// The log field name or tags key to use for the partition key.
    ///
    /// If the field does not exist in the log event or metric tags, a blank value will be used.
    ///
    /// If omitted, the key is not sent.
    ///
    /// Pulsar uses a hash of the key to choose the topic-partition or uses round-robin if the record has no key.
    #[configurable(metadata(docs::examples = "message"))]
    #[configurable(metadata(docs::examples = "my_field"))]
    pub(crate) partition_key_field: Option<OptionalTargetPath>,

    /// The log field name to use for the Pulsar properties key.
    ///
    /// If omitted, no properties will be written.
    pub properties_key: Option<OptionalTargetPath>,

    #[configurable(derived)]
    #[serde(default)]
    pub(crate) batch: PulsarBatchConfig,

    #[configurable(derived)]
    #[serde(default)]
    pub compression: PulsarCompression,

    #[configurable(derived)]
    pub encoding: EncodingConfig,

    #[configurable(derived)]
    pub(crate) auth: Option<PulsarAuthConfig>,

    #[configurable(derived)]
    #[serde(
        default,
        deserialize_with = "crate::serde::bool_or_struct",
        skip_serializing_if = "crate::serde::is_default"
    )]
    pub acknowledgements: AcknowledgementsConfig,

    #[configurable(derived)]
    #[serde(default)]
    pub connection_retry_options: Option<CustomConnectionRetryOptions>,
}

/// Event batching behavior.
#[configurable_component]
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct PulsarBatchConfig {
    /// The maximum amount of events in a batch before it is flushed.
    ///
    /// Note this is an unsigned 32 bit integer which is a smaller capacity than
    /// many of the other sink batch settings.
    #[configurable(metadata(docs::type_unit = "events"))]
    #[configurable(metadata(docs::examples = 1000))]
    pub max_events: Option<u32>,

    /// The maximum size of a batch before it is flushed.
    #[configurable(metadata(docs::type_unit = "bytes"))]
    pub max_bytes: Option<usize>,
}

/// Authentication configuration.
#[configurable_component]
#[derive(Clone, Debug)]
pub(crate) struct PulsarAuthConfig {
    /// Basic authentication name/username.
    ///
    /// This can be used either for basic authentication (username/password) or JWT authentication.
    /// When used for JWT, the value should be `token`.
    #[configurable(metadata(docs::examples = "${PULSAR_NAME}"))]
    #[configurable(metadata(docs::examples = "name123"))]
    name: Option<String>,

    /// Basic authentication password/token.
    ///
    /// This can be used either for basic authentication (username/password) or JWT authentication.
    /// When used for JWT, the value should be the signed JWT, in the compact representation.
    #[configurable(metadata(docs::examples = "${PULSAR_TOKEN}"))]
    #[configurable(metadata(docs::examples = "123456789"))]
    token: Option<SensitiveString>,

    #[configurable(derived)]
    oauth2: Option<OAuth2Config>,
}

/// OAuth2-specific authentication configuration.
#[configurable_component]
#[derive(Clone, Debug)]
pub struct OAuth2Config {
    /// The issuer URL.
    #[configurable(metadata(docs::examples = "${OAUTH2_ISSUER_URL}"))]
    #[configurable(metadata(docs::examples = "https://oauth2.issuer"))]
    issuer_url: String,

    /// The credentials URL.
    ///
    /// A data URL is also supported.
    #[configurable(metadata(docs::examples = "{OAUTH2_CREDENTIALS_URL}"))]
    #[configurable(metadata(docs::examples = "file:///oauth2_credentials"))]
    #[configurable(metadata(docs::examples = "data:application/json;base64,cHVsc2FyCg=="))]
    credentials_url: String,

    /// The OAuth2 audience.
    #[configurable(metadata(docs::examples = "${OAUTH2_AUDIENCE}"))]
    #[configurable(metadata(docs::examples = "pulsar"))]
    audience: Option<String>,

    /// The OAuth2 scope.
    #[configurable(metadata(docs::examples = "${OAUTH2_SCOPE}"))]
    #[configurable(metadata(docs::examples = "admin"))]
    scope: Option<String>,
}

/// Supported compression types for Pulsar.
#[configurable_component]
#[derive(Clone, Copy, Debug, Derivative)]
#[derivative(Default)]
#[serde(rename_all = "lowercase")]
pub enum PulsarCompression {
    /// No compression.
    #[derivative(Default)]
    None,

    /// LZ4.
    Lz4,

    /// Zlib.
    Zlib,

    /// Zstandard.
    Zstd,

    /// Snappy.
    Snappy,
}

#[configurable_component]
#[configurable(
    description = "Custom connection retry options configuration for the Pulsar client."
)]
#[derive(Clone, Debug)]
pub struct CustomConnectionRetryOptions {
    /// Minimum delay between connection retries.
    #[configurable(metadata(docs::type_unit = "milliseconds"))]
    pub min_backoff_ms: Option<u64>,

    /// Maximum delay between reconnection retries.
    #[configurable(metadata(docs::type_unit = "seconds"))]
    #[configurable(metadata(docs::examples = 30))]
    pub max_backoff_secs: Option<u64>,

    /// Maximum number of connection retries.
    #[configurable(metadata(docs::examples = 12))]
    pub max_retries: Option<u32>,

    /// Time limit to establish a connection.
    #[configurable(metadata(docs::type_unit = "seconds"))]
    #[configurable(metadata(docs::examples = 10))]
    pub connection_timeout_secs: Option<u64>,

    /// Keep-alive interval for each broker connection.
    #[configurable(metadata(docs::type_unit = "seconds"))]
    #[configurable(metadata(docs::examples = 60))]
    pub keep_alive_secs: Option<u64>,
}

impl Default for PulsarSinkConfig {
    fn default() -> Self {
        Self {
            endpoint: "pulsar://127.0.0.1:6650".to_string(),
            topic: Template::try_from("topic-1234")
                .expect("Unable to parse default template topic"),
            producer_name: None,
            properties_key: None,
            partition_key_field: None,
            batch: Default::default(),
            compression: Default::default(),
            encoding: TextSerializerConfig::default().into(),
            auth: None,
            acknowledgements: Default::default(),
            connection_retry_options: None,
        }
    }
}

impl PulsarSinkConfig {
    pub(crate) async fn create_pulsar_client(&self) -> Result<Pulsar<TokioExecutor>, PulsarError> {
        let mut builder = Pulsar::builder(&self.endpoint, TokioExecutor);
        if let Some(auth) = &self.auth {
            builder = match (
                auth.name.as_ref(),
                auth.token.as_ref(),
                auth.oauth2.as_ref(),
            ) {
                (Some(name), Some(token), None) => builder.with_auth(Authentication {
                    name: name.clone(),
                    data: token.inner().as_bytes().to_vec(),
                }),
                (None, None, Some(oauth2)) => builder.with_auth_provider(
                    OAuth2Authentication::client_credentials(OAuth2Params {
                        issuer_url: oauth2.issuer_url.clone(),
                        credentials_url: oauth2.credentials_url.clone(),
                        audience: oauth2.audience.clone(),
                        scope: oauth2.scope.clone(),
                    }),
                ),
                _ => return Err(PulsarError::Authentication(AuthenticationError::Custom(
                    "Invalid auth config: can only specify name and token or oauth2 configuration"
                        .to_string(),
                ))),
            };
        }

        // Apply configuration for reconnection exponential backoff.
        let default_retry_options = ConnectionRetryOptions::default();
        let retry_options =
            self.connection_retry_options
                .as_ref()
                .map_or(default_retry_options.clone(), |opts| {
                    ConnectionRetryOptions {
                        min_backoff: opts
                            .min_backoff_ms
                            .map_or(default_retry_options.min_backoff, |ms| {
                                Duration::from_millis(ms)
                            }),
                        max_backoff: opts
                            .max_backoff_secs
                            .map_or(default_retry_options.max_backoff, |secs| {
                                Duration::from_secs(secs)
                            }),
                        max_retries: opts
                            .max_retries
                            .unwrap_or(default_retry_options.max_retries),
                        connection_timeout: opts
                            .connection_timeout_secs
                            .map_or(default_retry_options.connection_timeout, |secs| {
                                Duration::from_secs(secs)
                            }),
                        keep_alive: opts
                            .keep_alive_secs
                            .map_or(default_retry_options.keep_alive, |secs| {
                                Duration::from_secs(secs)
                            }),
                    }
                });

        builder = builder.with_connection_retry_options(retry_options);

        // Apply configuration for retrying Pulsar operations.
        let operation_retry_opts = OperationRetryOptions::default();
        builder = builder.with_operation_retry_options(operation_retry_opts);

        builder.build().await
    }

    pub(crate) fn build_producer_options(&self) -> ProducerOptions {
        let mut opts = ProducerOptions {
            encrypted: None,
            access_mode: Some(0),
            metadata: Default::default(),
            schema: None,
            batch_size: self.batch.max_events,
            batch_byte_size: self.batch.max_bytes,
            compression: None,
        };

        match &self.compression {
            PulsarCompression::None => opts.compression = Some(compression::Compression::None),
            PulsarCompression::Lz4 => {
                opts.compression = Some(compression::Compression::Lz4(
                    compression::CompressionLz4::default(),
                ))
            }
            PulsarCompression::Zlib => {
                opts.compression = Some(compression::Compression::Zlib(
                    compression::CompressionZlib::default(),
                ))
            }
            PulsarCompression::Zstd => {
                opts.compression = Some(compression::Compression::Zstd(
                    compression::CompressionZstd::default(),
                ))
            }
            PulsarCompression::Snappy => {
                opts.compression = Some(compression::Compression::Snappy(
                    compression::CompressionSnappy::default(),
                ))
            }
        }

        if let SerializerConfig::Avro { avro } = self.encoding.config() {
            opts.schema = Some(proto::Schema {
                schema_data: avro.schema.as_bytes().into(),
                r#type: proto::schema::Type::Avro as i32,
                ..Default::default()
            });
        }
        opts
    }
}

impl GenerateConfig for PulsarSinkConfig {
    fn generate_config() -> toml::Value {
        toml::Value::try_from(Self::default()).unwrap()
    }
}

#[async_trait::async_trait]
#[typetag::serde(name = "pulsar")]
impl SinkConfig for PulsarSinkConfig {
    async fn build(&self, _cx: SinkContext) -> crate::Result<(VectorSink, Healthcheck)> {
        let client = self
            .create_pulsar_client()
            .await
            .context(super::sink::CreatePulsarSinkSnafu)?;

        let sink = PulsarSink::new(client, self.clone())?;

        let hc = healthcheck(self.clone()).boxed();

        Ok((VectorSink::from_event_streamsink(sink), hc))
    }

    fn input(&self) -> Input {
        let requirement =
            schema::Requirement::empty().optional_meaning("timestamp", Kind::timestamp());

        Input::new(self.encoding.config().input_type() & (DataType::Log | DataType::Metric))
            .with_schema_requirement(requirement)
    }

    fn acknowledgements(&self) -> &AcknowledgementsConfig {
        &self.acknowledgements
    }
}