Skip to main content

risingwave_connector/parser/
utils.rs

1// Copyright 2024 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::collections::BTreeMap;
16
17use anyhow::Context;
18use bytes::Bytes;
19use reqwest::Url;
20use risingwave_common::bail;
21use risingwave_common::types::{Datum, DatumCow, DatumRef, ScalarRefImpl};
22use risingwave_pb::data::DataType as PbDataType;
23
24use crate::aws_utils::load_file_descriptor_from_s3;
25use crate::connector_common::AwsAuthProps;
26use crate::error::ConnectorResult;
27use crate::source::SourceMeta;
28
29macro_rules! log_error {
30    ($name:expr, $err:expr, $message:expr) => {
31        if let Ok(suppressed_count) = LOG_SUPPRESSOR.check() {
32            tracing::error!(
33                column = $name,
34                error = %$err.as_report(),
35                suppressed_count,
36                $message,
37            );
38        }
39    };
40}
41pub(crate) use log_error;
42
43fn get_topic<'a>(
44    props: &'a BTreeMap<String, String>,
45    connector_topic_key: &str,
46) -> ConnectorResult<&'a String> {
47    const TOPIC_KEY: &str = "topic";
48
49    if let Some(topic) = props.get(connector_topic_key) {
50        return Ok(topic);
51    }
52    if let Some(topic) = props.get(TOPIC_KEY) {
53        return Ok(topic);
54    }
55
56    bail!("Must specify '{}' or '{}'", connector_topic_key, TOPIC_KEY)
57}
58
59/// Get the Kafka topic name.
60pub(super) fn get_kafka_topic(props: &BTreeMap<String, String>) -> ConnectorResult<&String> {
61    get_topic(props, "kafka.topic")
62}
63
64/// Get the Pulsar topic name.
65pub(super) fn get_pulsar_topic(props: &BTreeMap<String, String>) -> ConnectorResult<&String> {
66    get_topic(props, "pulsar.topic")
67}
68
69/// download bytes from http(s) url
70pub(super) async fn download_from_http(location: &Url) -> ConnectorResult<Bytes> {
71    let res = reqwest::get(location.clone())
72        .await
73        .with_context(|| format!("failed to make request to {location}"))?
74        .error_for_status()
75        .with_context(|| format!("http request failed for {location}"))?;
76
77    let bytes = res
78        .bytes()
79        .await
80        .with_context(|| format!("failed to read HTTP body of {location}"))?;
81
82    Ok(bytes)
83}
84
85// For parser that doesn't support key currently
86#[macro_export]
87macro_rules! only_parse_payload {
88    ($self:ident, $payload:ident, $writer:ident) => {
89        if let Some(payload) = $payload {
90            $self.parse_inner(payload, $writer).await
91        } else {
92            risingwave_common::bail!("empty payload with non-empty key")
93        }
94    };
95}
96
97/// Load raw bytes from:
98/// * local file, for on-premise or testing.
99/// * http/https, for common usage.
100/// * s3 file location format: <s3://bucket_name/file_name>
101pub(super) async fn bytes_from_url(
102    url: &Url,
103    config: Option<&AwsAuthProps>,
104) -> ConnectorResult<Vec<u8>> {
105    match (url.scheme(), config) {
106        // TODO(Tao): support local file only when it's compiled in debug mode.
107        ("file", _) => {
108            let path = url
109                .to_file_path()
110                .ok()
111                .with_context(|| format!("illegal path: {url}"))?;
112            Ok(std::fs::read(&path)
113                .with_context(|| format!("failed to read file from `{}`", path.display()))?)
114        }
115        ("https" | "http", _) => Ok(download_from_http(url).await?.into()),
116        ("s3", Some(config)) => load_file_descriptor_from_s3(url, config).await,
117        (scheme, _) => bail!("path scheme `{scheme}` is not supported"),
118    }
119}
120
121pub fn extract_timestamp_from_meta(meta: &SourceMeta) -> DatumRef<'_> {
122    match meta {
123        SourceMeta::Kafka(kafka_meta) => kafka_meta.extract_timestamp(),
124        SourceMeta::DebeziumCdc(cdc_meta) => cdc_meta.extract_timestamp(),
125        SourceMeta::Kinesis(kinesis_meta) => kinesis_meta.extract_timestamp(),
126        _ => None,
127    }
128}
129
130pub fn extract_headers_from_meta(meta: &SourceMeta) -> Option<Datum> {
131    match meta {
132        SourceMeta::Kafka(kafka_meta) => kafka_meta.extract_headers(), /* expect output of type `array[struct<varchar, bytea>]` */
133        SourceMeta::Pulsar(pulsar_meta) => pulsar_meta.extract_headers(), /* expect output of type `array[struct<varchar, bytea>]` */
134        SourceMeta::Nats(nats_meta) => nats_meta.extract_headers(), /* expect output of type `array[struct<varchar, bytea>]` */
135        _ => None,
136    }
137}
138
139pub fn extract_pulsar_message_id_data_from_meta(meta: &SourceMeta) -> Option<DatumRef<'_>> {
140    match meta {
141        SourceMeta::Pulsar(pulsar_meta) => pulsar_meta
142            .ack_message_id
143            .as_ref()
144            .map(|message_id| Some(ScalarRefImpl::Bytea(message_id))),
145        _ => None,
146    }
147}
148
149pub fn extract_header_inner_from_meta<'a>(
150    meta: &'a SourceMeta,
151    inner_field: &str,
152    data_type: Option<&PbDataType>,
153) -> Option<DatumCow<'a>> {
154    match meta {
155        SourceMeta::Kafka(kafka_meta) => kafka_meta.extract_header_inner(inner_field, data_type), /* expect output of type `bytea` or `varchar` */
156        SourceMeta::Pulsar(pulsar_meta) => pulsar_meta.extract_header_inner(inner_field, data_type),
157        SourceMeta::Nats(nats_meta) => nats_meta.extract_header_inner(inner_field, data_type), /* expect output of type `bytea` or `varchar` */
158        _ => None,
159    }
160}
161
162pub fn extract_subject_from_meta(meta: &SourceMeta) -> Option<DatumRef<'_>> {
163    match meta {
164        SourceMeta::Nats(nats_meta) => Some(nats_meta.extract_subject()),
165        _ => None,
166    }
167}
168
169#[cfg(test)]
170mod tests {
171    use async_nats::HeaderMap;
172    use risingwave_common::types::{DataType, ScalarImpl, ToOwnedDatum};
173
174    use super::*;
175    use crate::source::nats::source::NatsMeta;
176
177    fn nats_meta(subject: &str, headers: Option<HeaderMap>) -> SourceMeta {
178        SourceMeta::Nats(NatsMeta {
179            subject: subject.to_owned(),
180            headers,
181        })
182    }
183
184    #[test]
185    fn extract_headers_from_meta_dispatches_to_nats() {
186        let mut headers = HeaderMap::new();
187        headers.insert("k", "v");
188        let meta = nats_meta("subj", Some(headers));
189
190        let datum = extract_headers_from_meta(&meta).expect("outer Option");
191        assert!(matches!(datum, Some(ScalarImpl::List(_))));
192    }
193
194    #[test]
195    fn extract_header_inner_from_meta_dispatches_to_nats() {
196        let mut headers = HeaderMap::new();
197        headers.insert("trace", "abc");
198        let meta = nats_meta("subj", Some(headers));
199        let pb = DataType::Varchar.to_protobuf();
200
201        let result = extract_header_inner_from_meta(&meta, "trace", Some(&pb))
202            .unwrap()
203            .to_owned_datum();
204        assert_eq!(result, Some(ScalarImpl::Utf8("abc".into())));
205    }
206}