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
use std::collections::BTreeMap;
use std::io::Cursor;
use std::task::{Context, Poll};

use bytes::Bytes;
use chrono::Utc;
use databend_client::error::Error as DatabendError;
use databend_client::APIClient as DatabendAPIClient;
use futures::future::BoxFuture;
use rand::{thread_rng, Rng};
use rand_distr::Alphanumeric;
use snafu::Snafu;
use tower::Service;
use vector_lib::finalization::{EventFinalizers, EventStatus, Finalizable};
use vector_lib::request_metadata::{GroupedCountByteSize, MetaDescriptive, RequestMetadata};
use vector_lib::stream::DriverResponse;

use crate::{internal_events::EndpointBytesSent, sinks::util::retries::RetryLogic};

#[derive(Clone)]
pub struct DatabendRetryLogic;

impl RetryLogic for DatabendRetryLogic {
    type Error = DatabendError;
    type Response = DatabendResponse;

    fn is_retriable_error(&self, error: &Self::Error) -> bool {
        match error {
            DatabendError::InvalidResponse(qe) => match qe.code {
                429 => true,
                // general server error
                500 => true,
                // storage doesn't support presign operation
                3902 => false,
                // fail to parse stage attachment
                1046 => false,
                _ => false,
            },
            DatabendError::IO(_) => true,
            _ => false,
        }
    }
}

#[derive(Clone)]
pub struct DatabendService {
    client: DatabendAPIClient,
    table: String,
    file_format_options: BTreeMap<&'static str, &'static str>,
    copy_options: BTreeMap<&'static str, &'static str>,
}

#[derive(Clone)]
pub struct DatabendRequest {
    pub data: Bytes,
    pub finalizers: EventFinalizers,
    pub metadata: RequestMetadata,
}

impl Finalizable for DatabendRequest {
    fn take_finalizers(&mut self) -> EventFinalizers {
        self.finalizers.take_finalizers()
    }
}

impl MetaDescriptive for DatabendRequest {
    fn get_metadata(&self) -> &RequestMetadata {
        &self.metadata
    }

    fn metadata_mut(&mut self) -> &mut RequestMetadata {
        &mut self.metadata
    }
}

#[derive(Debug, Snafu)]
pub struct DatabendResponse {
    metadata: RequestMetadata,
}

impl DriverResponse for DatabendResponse {
    fn event_status(&self) -> EventStatus {
        EventStatus::Delivered
    }

    fn events_sent(&self) -> &GroupedCountByteSize {
        self.metadata.events_estimated_json_encoded_byte_size()
    }

    fn bytes_sent(&self) -> Option<usize> {
        Some(self.metadata.request_encoded_size())
    }
}

impl DatabendService {
    pub(super) fn new(
        client: DatabendAPIClient,
        table: String,
        file_format_options: BTreeMap<&'static str, &'static str>,
        copy_options: BTreeMap<&'static str, &'static str>,
    ) -> Result<Self, DatabendError> {
        if table.is_empty() {
            return Err(DatabendError::BadArgument("table is required".to_string()));
        }
        Ok(Self {
            client,
            table,
            file_format_options,
            copy_options,
        })
    }

    async fn new_stage_location(&self) -> String {
        let now = Utc::now().timestamp();
        let database = self
            .client
            .current_database()
            .await
            .unwrap_or("default".to_string());
        let suffix = thread_rng()
            .sample_iter(&Alphanumeric)
            .take(8)
            .map(char::from)
            .collect::<String>();
        format!("@~/vector/{}/{}/{}-{}", database, self.table, now, suffix,)
    }

    pub(crate) async fn insert_with_stage(&self, data: Bytes) -> Result<(), DatabendError> {
        let stage = self.new_stage_location().await;
        let size = data.len() as u64;
        let reader = Box::new(Cursor::new(data));
        self.client.upload_to_stage(&stage, reader, size).await?;
        let sql = format!("INSERT INTO `{}` VALUES", self.table);
        let _ = self
            .client
            .insert_with_stage(
                &sql,
                &stage,
                self.file_format_options.clone(),
                self.copy_options.clone(),
            )
            .await?;
        Ok(())
    }
}

impl Service<DatabendRequest> for DatabendService {
    type Response = DatabendResponse;
    type Error = DatabendError;
    type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;

    fn poll_ready(&mut self, _cx: &mut Context) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    fn call(&mut self, request: DatabendRequest) -> Self::Future {
        let service = self.clone();

        let future = async move {
            let metadata = request.get_metadata().clone();
            let protocol = service.client.scheme.as_str();
            let host_port = format!("{}:{}", service.client.host, service.client.port);
            let endpoint = host_port.as_str();
            let byte_size = request.data.len();
            service.insert_with_stage(request.data).await?;
            emit!(EndpointBytesSent {
                byte_size,
                protocol,
                endpoint,
            });
            Ok(DatabendResponse { metadata })
        };
        Box::pin(future)
    }
}