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
mod backend;
mod publisher;

use std::{
    fmt::Debug,
    sync::{Arc, Mutex},
};

use arrow_flight::{
    error::FlightError,
    sql::{client::FlightSqlServiceClient, Any, Command},
};
use ella_engine::{
    lazy::Lazy,
    registry::{Id, SchemaRef, TableRef},
    table::info::TableInfo,
    EllaConfig, Plan,
};
use prost::Message;
use tonic::{
    codegen::InterceptedService,
    metadata::{Ascii, MetadataValue},
    service::Interceptor,
    transport::Channel,
};

use crate::{
    gen::{self, engine_service_client::EngineServiceClient},
    table::RemoteTable,
};

use self::backend::RemoteBackend;
pub use self::publisher::FlightPublisher;

#[derive(Debug, Clone)]
pub struct EllaClient {
    flight: FlightSqlServiceClient<Channel>,
    engine: EngineServiceClient<InterceptedService<Channel, BearerAuth>>,
    config: Arc<Mutex<EllaConfig>>,
}

impl EllaClient {
    pub async fn connect(channel: Channel) -> crate::Result<Self> {
        let mut flight = FlightSqlServiceClient::new(channel.clone());
        let token = flight.handshake("", "").await?;
        let token =
            String::from_utf8(token.into()).map_err(|_| crate::ClientError::InvalidToken)?;
        flight.set_token(token.clone());

        let auth = BearerAuth::try_new(&token)?;
        let mut engine = EngineServiceClient::with_interceptor(channel, auth);

        let resp = engine
            .get_config(gen::GetConfigReq {
                scope: gen::ConfigScope::Connection.into(),
            })
            .await
            .map_err(crate::ClientError::Server)?;
        let config = serde_json::from_slice(&resp.into_inner().config)?;
        let config = Arc::new(Mutex::new(config));
        Ok(Self {
            flight,
            engine,
            config,
        })
    }

    pub async fn create_table(
        &self,
        table: TableRef<'_>,
        info: TableInfo,
        if_not_exists: bool,
        or_replace: bool,
    ) -> crate::Result<RemoteTable> {
        let mut this = self.clone();
        let req = gen::CreateTableReq {
            table: Some(table.into()),
            info: Some(info.try_into()?),
            if_not_exists,
            or_replace,
        };
        let resp = this
            .engine
            .create_table(req)
            .await
            .map_err(crate::ClientError::Server)?
            .into_inner();

        Ok(RemoteTable::new(
            resp.table.expect("expected table ID in response").into(),
            resp.info
                .expect("expected table info in response")
                .try_into()?,
            this,
        ))
    }

    pub async fn get_table(&self, table: TableRef<'_>) -> crate::Result<Option<RemoteTable>> {
        let mut this = self.clone();
        let resp = this
            .engine
            .get_table(gen::TableRef::from(table))
            .await
            .map_err(crate::ClientError::Server)?
            .into_inner();
        Ok(match (&resp.table, &resp.info) {
            (Some(table), Some(info)) => Some(RemoteTable::new(
                table.clone().into(),
                info.clone().try_into()?,
                this,
            )),
            (None, None) => None,
            (_, _) => panic!(
                "expected empty or fully-populated response, got: {:?}",
                resp
            ),
        })
    }

    pub async fn query<S: Into<String>>(&self, query: S) -> crate::Result<Lazy> {
        let mut this = self.clone();

        let info = this.flight.execute(query.into(), None).await?;
        let ticket = match info.endpoint.len() {
            0 => Err(crate::ClientError::MissingEndpoint),
            1 => info.endpoint[0]
                .ticket
                .as_ref()
                .ok_or_else(|| crate::ClientError::MissingTicket),
            _ => unimplemented!(),
        }?;
        let msg = Any::decode(&*ticket.ticket)?;
        let raw_plan = match Command::try_from(msg)? {
            Command::TicketStatementQuery(ticket) => ticket.statement_handle,
            cmd => {
                return Err(FlightError::DecodeError(format!(
                    "unexpected response command: {:?}",
                    cmd
                ))
                .into())
            }
        };
        let plan = Plan::from_bytes(&raw_plan)?;
        Ok(Lazy::new(plan, Arc::new(RemoteBackend::from(this))))
    }

    pub fn config(&self) -> EllaConfig {
        self.config.lock().unwrap().clone()
    }

    pub fn default_catalog(&self) -> Id<'static> {
        self.config.lock().unwrap().default_catalog.clone()
    }

    pub fn default_schema(&self) -> Id<'static> {
        self.config.lock().unwrap().default_schema.clone()
    }

    pub async fn set_config(&mut self, config: EllaConfig, persist: bool) -> crate::Result<()> {
        let scope = if persist {
            gen::ConfigScope::Cluster
        } else {
            gen::ConfigScope::Connection
        };
        let raw_config = serde_json::to_vec(&config)?;
        *self.config.lock().unwrap() = config;

        self.engine
            .set_config(gen::Config {
                scope: scope.into(),
                config: raw_config,
            })
            .await
            .map_err(crate::ClientError::Server)?;
        Ok(())
    }

    pub async fn use_catalog<'a>(&mut self, catalog: impl Into<Id<'a>>) -> crate::Result<()> {
        let catalog: Id<'static> = catalog.into().into_owned();
        let config = self
            .config()
            .into_builder()
            .default_catalog(catalog)
            .build();
        self.set_config(config, false).await?;

        Ok(())
    }

    pub async fn use_schema<'a>(&mut self, schema: impl Into<Id<'a>>) -> crate::Result<()> {
        let schema: Id<'static> = schema.into().into_owned();
        let config = self.config().into_builder().default_schema(schema).build();
        self.set_config(config, false).await?;

        Ok(())
    }

    pub async fn create_catalog<'a>(
        &mut self,
        catalog: impl Into<Id<'a>>,
        if_not_exists: bool,
    ) -> crate::Result<()> {
        let catalog: Id<'a> = catalog.into();
        self.engine
            .create_catalog(gen::CreateCatalogReq {
                catalog: catalog.to_string(),
                if_not_exists,
            })
            .await
            .map_err(crate::ClientError::Server)?;
        Ok(())
    }

    pub async fn create_schema<'a>(
        &mut self,
        schema: impl Into<SchemaRef<'a>>,
        if_not_exists: bool,
    ) -> crate::Result<()> {
        let schema: SchemaRef<'a> = schema.into();
        self.engine
            .create_schema(gen::CreateSchemaReq {
                catalog: schema.catalog.map(|c| c.to_string()),
                schema: schema.schema.to_string(),
                if_not_exists,
            })
            .await
            .map_err(crate::ClientError::Server)?;
        Ok(())
    }
}

#[derive(Debug, Clone)]
struct BearerAuth {
    payload: MetadataValue<Ascii>,
}

impl BearerAuth {
    fn try_new(token: &str) -> crate::Result<Self> {
        let payload = format!("Bearer {token}")
            .parse()
            .map_err(|_| crate::ClientError::InvalidToken)?;
        Ok(Self { payload })
    }
}

impl Interceptor for BearerAuth {
    fn call(
        &mut self,
        mut request: tonic::Request<()>,
    ) -> Result<tonic::Request<()>, tonic::Status> {
        request
            .metadata_mut()
            .insert("authorization", self.payload.clone());
        Ok(request)
    }
}