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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
//
// Copyright (c) Dell Inc., or its subsidiaries. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
#![allow(bare_trait_objects)]

//! Factory to create components in Pravega Rust client.
//!
//! Applications should always use this ClientFactory to initialize components.
//!
use crate::byte::reader::ByteReader;
use crate::byte::writer::ByteWriter;
use crate::event::reader_group::{ReaderGroup, ReaderGroupConfig, ReaderGroupConfigBuilder};
use crate::event::transactional_writer::TransactionalEventWriter;
use crate::event::writer::EventWriter;
use crate::segment::metadata::SegmentMetadataClient;
use crate::segment::raw_client::RawClientImpl;
use crate::segment::reader::AsyncSegmentReaderImpl;
use crate::sync::synchronizer::Synchronizer;
use crate::sync::table::{Table, TableError};
cfg_if::cfg_if! {
    if #[cfg(feature = "integration-test")] {
        use crate::test_utils::{RawClientWrapper, SegmentReaderWrapper};
    }
}

use crate::index::Fields;
use pravega_client_auth::DelegationTokenProvider;
use pravega_client_config::ClientConfig;
use pravega_client_shared::{DelegationToken, PravegaNodeUri, Scope, ScopedSegment, ScopedStream, WriterId};
use pravega_connection_pool::connection_pool::ConnectionPool;
use pravega_controller_client::mock_controller::MockController;
use pravega_controller_client::{ControllerClient, ControllerClientImpl};
use pravega_wire_protocol::connection_factory::{
    ConnectionFactory, ConnectionFactoryConfig, SegmentConnectionManager,
};

use crate::index::{IndexReader, IndexWriter};
use crate::util::meta::MetaClient;
use std::fmt;
use std::fmt::Debug;
use std::sync::Arc;
use tokio::runtime::{Handle, Runtime};
use tracing::info;

/// Applications should use ClientFactory to create resources they need.
///
/// ClientFactory contains a connection pool that is shared by all the readers and writers it creates.
/// It also contains a tokio runtime that is used to drive async tasks. Spawned tasks in readers and
/// writers are tied to this runtime.
///
/// Note that dropping Runtime in async context is not a good practice and it will have warning messages.
/// ClientFactory is the only place that's holding the Runtime, so it should not be used in any async contexts.
/// You can use ['ClientFactoryAsync'] in async contexts instead.
///
/// # Examples
/// ```no_run
/// use pravega_client_config::ClientConfigBuilder;
/// use pravega_client::client_factory::ClientFactory;
///
/// fn main() {
///    let config = ClientConfigBuilder::default()
///         .controller_uri("localhost:8000")
///         .build()
///         .expect("create config");
///     let client_factory = ClientFactory::new(config);
/// }
/// ```
/// ```no_run
/// use pravega_client_config::ClientConfigBuilder;
/// use pravega_client::client_factory::ClientFactoryAsync;
/// use tokio::runtime::Handle;
///
/// #[tokio::main]
/// async fn main() {
///    let config = ClientConfigBuilder::default()
///         .controller_uri("localhost:8000")
///         .build()
///         .expect("create config");
///     let handle = Handle::try_current().expect("get current runtime handle");
///     let client_factory = ClientFactoryAsync::new(config, handle);
/// }
/// ```
/// [`ClientFactoryAsync`]: ClientFactoryAsync
pub struct ClientFactory {
    runtime: Runtime,
    client_factory_async: ClientFactoryAsync,
}

impl ClientFactory {
    pub fn new(config: ClientConfig) -> ClientFactory {
        let rt = tokio::runtime::Runtime::new().expect("create runtime");
        ClientFactory::new_with_runtime(config, rt)
    }

    pub fn new_with_runtime(config: ClientConfig, rt: Runtime) -> ClientFactory {
        let async_factory = ClientFactoryAsync::new(config, rt.handle().clone());
        ClientFactory {
            runtime: rt,
            client_factory_async: async_factory,
        }
    }

    pub fn runtime(&self) -> &Runtime {
        &self.runtime
    }

    pub fn runtime_handle(&self) -> Handle {
        self.runtime.handle().clone()
    }

    pub fn config(&self) -> &ClientConfig {
        self.client_factory_async.config()
    }

    pub fn controller_client(&self) -> &dyn ControllerClient {
        self.client_factory_async.controller_client()
    }

    pub fn create_event_writer(&self, stream: ScopedStream) -> EventWriter {
        self.client_factory_async.create_event_writer(stream)
    }

    pub async fn create_reader_group(&self, reader_group_name: String, stream: ScopedStream) -> ReaderGroup {
        info!(
            "Creating reader group {:?} to read data from stream {:?}",
            reader_group_name, stream
        );
        self.client_factory_async
            .create_reader_group(reader_group_name, stream)
            .await
    }

    ///
    /// Create a Reader Group based on the ReaderGroupConfig.
    ///
    pub async fn create_reader_group_with_config(
        &self,
        reader_group_name: String,
        reader_group_config: ReaderGroupConfig,
        scope: Scope,
    ) -> ReaderGroup {
        info!(
            "Creating reader group {:?} to read data from streams {:?}",
            reader_group_name,
            reader_group_config.get_streams()
        );
        self.client_factory_async
            .create_reader_group_with_config(scope, reader_group_name, reader_group_config)
            .await
    }

    ///
    /// Delete a ReaderGroup.
    ///
    pub async fn delete_reader_group(
        &self,
        scope: Scope,
        reader_group_name: String,
    ) -> Result<(), TableError> {
        info!(
            "Deleting reader group {:?} under scope {:?}",
            reader_group_name, scope
        );
        self.client_factory_async
            .delete_reader_group(scope, reader_group_name)
            .await
    }

    pub async fn create_transactional_event_writer(
        &self,
        stream: ScopedStream,
        writer_id: WriterId,
    ) -> TransactionalEventWriter {
        self.client_factory_async
            .create_transactional_event_writer(stream, writer_id)
            .await
    }

    pub async fn create_byte_writer(&self, stream: ScopedStream) -> ByteWriter {
        self.client_factory_async.create_byte_writer(stream).await
    }

    pub async fn create_byte_reader(&self, stream: ScopedStream) -> ByteReader {
        self.client_factory_async.create_byte_reader(stream).await
    }

    pub async fn create_index_writer<T: Fields + PartialOrd + PartialEq + Debug>(
        &self,
        stream: ScopedStream,
    ) -> IndexWriter<T> {
        self.client_factory_async.create_index_writer(stream).await
    }

    pub async fn create_index_reader(&self, stream: ScopedStream) -> IndexReader {
        self.client_factory_async.create_index_reader(stream).await
    }

    pub async fn create_table(&self, scope: Scope, name: String) -> Table {
        self.client_factory_async.create_table(scope, name).await
    }

    pub async fn create_synchronizer(&self, scope: Scope, name: String) -> Synchronizer {
        self.client_factory_async.create_synchronizer(scope, name).await
    }

    pub fn to_async(&self) -> ClientFactoryAsync {
        self.client_factory_async.clone()
    }

    pub(crate) async fn create_async_segment_reader(&self, segment: ScopedSegment) -> AsyncSegmentReaderImpl {
        self.client_factory_async
            .create_async_segment_reader(segment)
            .await
    }

    pub(crate) async fn create_raw_client(&self, segment: &ScopedSegment) -> RawClientImpl<'_> {
        self.client_factory_async.create_raw_client(segment).await
    }

    pub(crate) fn create_raw_client_for_endpoint(&self, endpoint: PravegaNodeUri) -> RawClientImpl<'_> {
        self.client_factory_async.create_raw_client_for_endpoint(endpoint)
    }

    pub(crate) async fn create_delegation_token_provider(
        &self,
        stream: ScopedStream,
    ) -> DelegationTokenProvider {
        self.client_factory_async
            .create_delegation_token_provider(stream)
            .await
    }

    pub(crate) async fn create_segment_metadata_client(
        &self,
        segment: ScopedSegment,
    ) -> SegmentMetadataClient {
        self.client_factory_async
            .create_segment_metadata_client(segment)
            .await
    }

    #[doc(hidden)]
    #[cfg(feature = "integration-test")]
    pub async fn create_raw_client_wrapper(&self, segment: &ScopedSegment) -> RawClientWrapper<'_> {
        let endpoint = self
            .client_factory_async
            .controller_client
            .get_endpoint_for_segment(segment)
            .await
            .expect("get endpoint for segment");
        RawClientWrapper::new(
            &self.client_factory_async.connection_pool,
            endpoint,
            self.client_factory_async.config.request_timeout,
        )
    }

    #[doc(hidden)]
    #[cfg(feature = "integration-test")]
    pub async fn create_segment_reader_wrapper(&self, segment: ScopedSegment) -> SegmentReaderWrapper {
        SegmentReaderWrapper::new(
            segment.clone(),
            self.to_async(),
            self.client_factory_async
                .create_delegation_token_provider(ScopedStream::from(&segment))
                .await,
        )
        .await
    }
}

#[derive(Clone)]
pub struct ClientFactoryAsync {
    connection_pool: Arc<ConnectionPool<SegmentConnectionManager>>,
    controller_client: Arc<Box<dyn ControllerClient>>,
    config: Arc<ClientConfig>,
    runtime_handle: Handle,
}

impl ClientFactoryAsync {
    pub fn new(config: ClientConfig, handle: Handle) -> Self {
        let cf = ConnectionFactory::create(ConnectionFactoryConfig::from(&config));
        let pool = ConnectionPool::new(SegmentConnectionManager::new(cf, config.max_connections_in_pool));
        let controller = if config.mock {
            Box::new(MockController::new(config.controller_uri.clone())) as Box<dyn ControllerClient>
        } else {
            Box::new(ControllerClientImpl::new(config.clone(), &handle)) as Box<dyn ControllerClient>
        };
        ClientFactoryAsync {
            connection_pool: Arc::new(pool),
            controller_client: Arc::new(controller),
            config: Arc::new(config),
            runtime_handle: handle,
        }
    }
    pub fn config(&self) -> &ClientConfig {
        &self.config
    }

    pub fn create_event_writer(&self, stream: ScopedStream) -> EventWriter {
        EventWriter::new(stream, self.clone())
    }

    pub async fn create_stream_meta_client(&self, stream: ScopedStream) -> MetaClient {
        MetaClient::new(stream, self.clone())
    }

    ///
    /// Create a ReaderGroup with the specified name to read from the specified Stream.
    /// The readers will read from the HEAD/beginning of the Stream.
    ///
    pub async fn create_reader_group(&self, reader_group_name: String, stream: ScopedStream) -> ReaderGroup {
        let scope = stream.scope.clone();
        let rg_config = ReaderGroupConfigBuilder::default().add_stream(stream).build();
        ReaderGroup::create(scope, reader_group_name, rg_config, self.clone()).await
    }

    ///
    /// Create a ReaderGroup with the streams configured in the ReaderGroupConfig.
    ///
    pub async fn create_reader_group_with_config(
        &self,
        scope: Scope,
        reader_group_name: String,
        rg_config: ReaderGroupConfig,
    ) -> ReaderGroup {
        ReaderGroup::create(scope, reader_group_name, rg_config, self.clone()).await
    }

    ///
    /// Delete a ReaderGroup given for a given scope.
    ///
    pub async fn delete_reader_group(
        &self,
        scope: Scope,
        reader_group_name: String,
    ) -> Result<(), TableError> {
        ReaderGroup::delete(scope, reader_group_name, self.clone()).await
    }

    pub async fn create_transactional_event_writer(
        &self,
        stream: ScopedStream,
        writer_id: WriterId,
    ) -> TransactionalEventWriter {
        TransactionalEventWriter::new(stream, writer_id, self.clone()).await
    }

    pub async fn create_byte_writer(&self, stream: ScopedStream) -> ByteWriter {
        ByteWriter::new(stream, self.clone()).await
    }

    pub async fn create_byte_reader(&self, stream: ScopedStream) -> ByteReader {
        ByteReader::new(stream, self.clone(), self.config().reader_wrapper_buffer_size()).await
    }

    pub async fn create_index_writer<T: Fields + PartialOrd + PartialEq + Debug>(
        &self,
        stream: ScopedStream,
    ) -> IndexWriter<T> {
        IndexWriter::new(self.clone(), stream).await
    }

    pub async fn create_index_reader(&self, stream: ScopedStream) -> IndexReader {
        IndexReader::new(self.clone(), stream).await
    }

    pub async fn create_table(&self, scope: Scope, name: String) -> Table {
        Table::new(scope, name, self.clone())
            .await
            .expect("Failed to create Table map")
    }

    pub async fn create_synchronizer(&self, scope: Scope, name: String) -> Synchronizer {
        Synchronizer::new(scope, name, self.clone()).await
    }

    pub fn controller_client(&self) -> &dyn ControllerClient {
        &**self.controller_client
    }

    pub fn runtime_handle(&self) -> Handle {
        self.runtime_handle.clone()
    }

    pub(crate) async fn create_async_segment_reader(&self, segment: ScopedSegment) -> AsyncSegmentReaderImpl {
        AsyncSegmentReaderImpl::new(
            segment.clone(),
            self.clone(),
            self.create_delegation_token_provider(ScopedStream::from(&segment))
                .await,
        )
        .await
    }

    pub(crate) async fn create_raw_client(&self, segment: &ScopedSegment) -> RawClientImpl<'_> {
        let endpoint = self
            .controller_client
            .get_endpoint_for_segment(segment)
            .await
            .expect("get endpoint for segment");
        RawClientImpl::new(&self.connection_pool, endpoint, self.config.request_timeout)
    }

    pub(crate) fn create_raw_client_for_endpoint(&self, endpoint: PravegaNodeUri) -> RawClientImpl<'_> {
        RawClientImpl::new(&self.connection_pool, endpoint, self.config.request_timeout)
    }

    pub(crate) async fn create_segment_metadata_client(
        &self,
        segment: ScopedSegment,
    ) -> SegmentMetadataClient {
        SegmentMetadataClient::new(segment, self.clone()).await
    }

    pub(crate) async fn create_delegation_token_provider(
        &self,
        stream: ScopedStream,
    ) -> DelegationTokenProvider {
        let token_provider = DelegationTokenProvider::new(stream);
        if !self.config.is_auth_enabled {
            let empty_token = DelegationToken::new("".to_string(), None);
            token_provider.populate(empty_token).await;
        }
        token_provider
    }

    pub(crate) fn get_connection_pool(&self) -> &ConnectionPool<SegmentConnectionManager> {
        &self.connection_pool
    }
}

impl fmt::Debug for ClientFactoryAsync {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ClientFactoryInternal")
            .field("connection pool", &self.connection_pool)
            .field("client config,", &self.config)
            .finish()
    }
}