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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
use crate::commands::*;
use crate::result::*;
use std::fmt;
use std::io::{BufRead, BufReader, BufWriter, Write};
use std::net::{TcpStream, ToSocketAddrs};

const DEFAULT_SONIC_PROTOCOL_VERSION: usize = 1;
const UNINITIALIZED_MODE_MAX_BUFFER_SIZE: usize = 200;

macro_rules! init_commands {
    (
        $(
            $(#[$outer:meta])*
            use $cmd_name:ident
            for fn $fn_name:ident
            $(<$($lt:lifetime)+>)? (
                $($args:tt)*
            )
            $(where mode is $condition:expr)?;
        )*
    ) => {
        $(
            init_commands!(
                $(#[$outer])*
                use $cmd_name
                for fn $fn_name $(<$($lt)+>)? (
                    $($args)*
                )
                $(where $condition)?
            );
        )*
    };

    (
        $(#[$outer:meta])*
        use $cmd_name:ident
        for fn $fn_name:ident $(<$($lt:lifetime)+>)? (
            $($arg_name:ident : $arg_type:ty $( => $arg_value:expr)?,)*
        )
        $(where $condition:expr)?
    ) => {
        $(#[$outer])*
        pub fn $fn_name $(<$($lt)+>)? (
            &self,
            $($arg_name: $arg_type),*
        ) -> $crate::result::Result<
            <$cmd_name as $crate::commands::StreamCommand>::Response,
        > {
            $(
                let mode = self.mode.clone();
                if mode != Some($condition) {
                    return Err(Error::new(
                        ErrorKind::UnsupportedCommand((
                            stringify!($fn_name), 
                            mode,
                        ))
                    ));
                }
            )?
            let command = $cmd_name { $($arg_name $(: $arg_value)?,)* ..Default::default() };
            self.run_command(command)
        }
    };
}

/// Channel modes supported by sonic search backend.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ChannelMode {
    /// Sonic server search channel mode.
    ///
    /// In this mode you can use `query`, `suggest`, `ping` and `quit` commands.
    ///
    /// Note: This mode requires enabling the `search` feature.
    #[cfg(feature = "search")]
    Search,

    /// Sonic server ingest channel mode.
    ///
    /// In this mode you can use `push`, `pop`, `flushc`, `flushb`, `flusho`,
    /// `bucket_count`, `object_count`, `word_count`, `ping` and `quit` commands.
    ///
    /// Note: This mode requires enabling the `ingest` feature.
    #[cfg(feature = "ingest")]
    Ingest,

    /// Sonic server control channel mode.
    ///
    /// In this mode you can use `consolidate`, `backup`, `restore`,
    /// `ping` and `quit` commands.
    ///
    /// Note: This mode requires enabling the `control` feature.
    #[cfg(feature = "control")]
    Control,
}

impl ChannelMode {
    /// Converts enum to &str
    pub fn to_str(&self) -> &str {
        match self {
            #[cfg(feature = "search")]
            ChannelMode::Search => "search",

            #[cfg(feature = "ingest")]
            ChannelMode::Ingest => "ingest",

            #[cfg(feature = "control")]
            ChannelMode::Control => "control",
        }
    }
}

impl fmt::Display for ChannelMode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::result::Result<(), fmt::Error> {
        write!(f, "{}", self.to_str())
    }
}

/// Root and Heart of this library.
///
/// You can connect to the sonic search backend and run all supported protocol methods.
///
#[derive(Debug)]
pub struct SonicChannel {
    stream: TcpStream,
    mode: Option<ChannelMode>, // None – Uninitialized mode
    max_buffer_size: usize,
    protocol_version: usize,
}

impl SonicChannel {
    fn write<SC: StreamCommand>(&self, command: &SC) -> Result<()> {
        let mut writer = BufWriter::with_capacity(self.max_buffer_size, &self.stream);
        let message = command.message();
        dbg!(&message);
        writer
            .write_all(message.as_bytes())
            .map_err(|_| Error::new(ErrorKind::WriteToStream))?;
        Ok(())
    }

    fn read(&self, max_read_lines: usize) -> Result<String> {
        let mut reader = BufReader::with_capacity(self.max_buffer_size, &self.stream);
        let mut message = String::new();

        let mut lines_read = 0;
        while lines_read < max_read_lines {
            reader
                .read_line(&mut message)
                .map_err(|_| Error::new(ErrorKind::ReadStream))?;
            lines_read += 1;
        }

        Ok(message)
    }

    fn run_command<SC: StreamCommand>(&self, command: SC) -> Result<SC::Response> {
        self.write(&command)?;
        let message = self.read(SC::READ_LINES_COUNT)?;
        command.receive(message)
    }

    fn connect<A: ToSocketAddrs>(addr: A) -> Result<Self> {
        let stream =
            TcpStream::connect(addr).map_err(|_| Error::new(ErrorKind::ConnectToServer))?;

        let channel = SonicChannel {
            stream,
            mode: None,
            max_buffer_size: UNINITIALIZED_MODE_MAX_BUFFER_SIZE,
            protocol_version: DEFAULT_SONIC_PROTOCOL_VERSION,
        };

        let message = channel.read(1)?;
        dbg!(&message);
        // TODO: need to add support for versions
        if message.starts_with("CONNECTED") {
            Ok(channel)
        } else {
            Err(Error::new(ErrorKind::ConnectToServer))
        }
    }

    fn start<S: ToString>(&mut self, mode: ChannelMode, password: S) -> Result<()> {
        if self.mode.is_some() {
            return Err(Error::new(ErrorKind::RunCommand));
        }

        let command = StartCommand {
            mode,
            password: password.to_string(),
        };
        let response = self.run_command(command)?;

        self.max_buffer_size = response.max_buffer_size;
        self.protocol_version = response.protocol_version;
        self.mode = Some(response.mode);

        Ok(())
    }

    /// Connect to the search backend in chosen mode.
    ///
    /// I think we shouldn't separate commands connect and start because we haven't
    /// possibility to change channel in sonic server, if we already chosen one of them. 🤔
    ///
    /// ```rust,no_run
    /// use sonic_channel::*;
    ///
    /// fn main() -> result::Result<()> {
    ///     let channel = SonicChannel::connect_with_start(
    ///         ChannelMode::Search,
    ///         "localhost:1491",
    ///         "SecretPassword"
    ///     )?;
    ///
    ///     // Now you can use all method of Search channel.
    ///     let objects = channel.query("search", "default", "beef");
    ///     
    ///     Ok(())
    /// }
    /// ```
    pub fn connect_with_start<A, S>(mode: ChannelMode, addr: A, password: S) -> Result<Self>
    where
        A: ToSocketAddrs,
        S: ToString,
    {
        let mut channel = Self::connect(addr)?;
        channel.start(mode, password)?;
        Ok(channel)
    }

    init_commands! {
        #[doc=r#"
        Stop connection.

        ```rust,no_run
        # use sonic_channel::*;
        # fn main() -> result::Result<()> {
        let channel = SonicChannel::connect_with_start(
            ChannelMode::Search,
            "localhost:1491",
            "SecretPassword",
        )?;

        channel.quit()?;
        # Ok(())
        # }
        "#]
        use QuitCommand for fn quit();

        #[doc=r#"
        Ping server.

        ```rust,no_run
        # use sonic_channel::*;
        # fn main() -> result::Result<()> {
        let channel = SonicChannel::connect_with_start(
            ChannelMode::Search,
            "localhost:1491",
            "SecretPassword",
        )?;

        channel.ping()?;
        # Ok(())
        # }
        "#]
        use PingCommand for fn ping();
    }

    #[cfg(feature = "ingest")]
    init_commands! {
        #[doc=r#"
        Push search data in the index.

        Note: This method requires enabling the `ingest` feature and start
        connection in Ingest mode.

        ```rust,no_run
        # use sonic_channel::*;
        # fn main() -> result::Result<()> {
        let ingest_channel = SonicChannel::connect_with_start(
            ChannelMode::Ingest,
            "localhost:1491",
            "SecretPassword",
        )?;

        let result = ingest_channel.push(
            "search",
            "default",
            "recipe:295",
            "Sweet Teriyaki Beef Skewers",
        )?;
        assert_eq!(result, true);
        # Ok(())
        # }
        ```
        "#]
        use PushCommand for fn push<'a>(
            collection: &'a str,
            bucket: &'a str,
            object: &'a str,
            text: &'a str,
        ) where mode is ChannelMode::Ingest;

        #[doc=r#"
        Push search data in the index with locale parameter in ISO 639-3 code.

        Note: This method requires enabling the `ingest` feature and start 
        connection in Ingest mode.

        ```rust,no_run
        # use sonic_channel::*;
        # fn main() -> result::Result<()> {
        let ingest_channel = SonicChannel::connect_with_start(
            ChannelMode::Ingest,
            "localhost:1491",
            "SecretPassword",
        )?;

        let result = ingest_channel.push_with_locale(
            "search",
            "default",
            "recipe:296",
            "Гренки с жареным картофелем и сыром",
            "rus",
        )?;
        assert_eq!(result, true);
        # Ok(())
        # }
        ```
        "#]
        use PushCommand for fn push_with_locale<'a>(
            collection: &'a str,
            bucket: &'a str,
            object: &'a str,
            text: &'a str,
            locale: &'a str => Some(locale),
        ) where mode is ChannelMode::Ingest;

        #[doc=r#"
        Pop search data from the index. Returns removed words count as usize type.

        Note: This method requires enabling the `ingest` feature and start 
        connection in Ingest mode.

        ```rust,no_run
        # use sonic_channel::*;
        # fn main() -> result::Result<()> {
        let ingest_channel = SonicChannel::connect_with_start(
            ChannelMode::Ingest,
            "localhost:1491",
            "SecretPassword",
        )?;

        let result = ingest_channel.pop("search", "default", "recipe:295", "beef")?;
        assert_eq!(result, 1);
        # Ok(())
        # }
        ```
        "#]
        use PopCommand for fn pop<'a>(
            collection: &'a str,
            bucket: &'a str,
            object: &'a str,
            text: &'a str,
        ) where mode is ChannelMode::Ingest;

        #[doc=r#"
        Flush all indexed data from collections.

        Note: This method requires enabling the `ingest` feature and start 
        connection in Ingest mode.

        ```rust,no_run
        # use sonic_channel::*;
        # fn main() -> result::Result<()> {
        let ingest_channel = SonicChannel::connect_with_start(
            ChannelMode::Ingest,
            "localhost:1491",
            "SecretPassword",
        )?;

        let flushc_count = ingest_channel.flushc("search")?;
        dbg!(flushc_count);
        # Ok(())
        # }
        ```
        "#]
        use FlushCommand for fn flushc<'a>(
            collection: &'a str,
        ) where mode is ChannelMode::Ingest;

        #[doc=r#"
        Flush all indexed data from bucket in a collection.

        Note: This method requires enabling the `ingest` feature and start 
        connection in Ingest mode.

        ```rust,no_run
        # use sonic_channel::*;
        # fn main() -> result::Result<()> {
        let ingest_channel = SonicChannel::connect_with_start(
            ChannelMode::Ingest,
            "localhost:1491",
            "SecretPassword",
        )?;

        let flushb_count = ingest_channel.flushb("search", "default")?;
        dbg!(flushb_count);
        # Ok(())
        # }
        ```
        "#]
        use FlushCommand for fn flushb<'a>(
            collection: &'a str,
            bucket: &'a str => Some(bucket),
        ) where mode is ChannelMode::Ingest;

        #[doc=r#"
        Flush all indexed data from an object in a bucket in collection.

        Note: This method requires enabling the `ingest` feature and start 
        connection in Ingest mode.

        ```rust,no_run
        # use sonic_channel::*;
        # fn main() -> result::Result<()> {
        let ingest_channel = SonicChannel::connect_with_start(
            ChannelMode::Ingest,
            "localhost:1491",
            "SecretPassword",
        )?;

        let flusho_count = ingest_channel.flusho("search", "default", "recipe:296")?;
        dbg!(flusho_count);
        # Ok(())
        # }
        ```
        "#]
        use FlushCommand for fn flusho<'a>(
            collection: &'a str,
            bucket: &'a str => Some(bucket),
            object: &'a str => Some(object),
        ) where mode is ChannelMode::Ingest;

        #[doc=r#"
        Bucket count in indexed search data of your collection.

        Note: This method requires enabling the `ingest` feature and start 
        connection in Ingest mode.

        ```rust,no_run
        # use sonic_channel::*;
        # fn main() -> result::Result<()> {
        let ingest_channel = SonicChannel::connect_with_start(
            ChannelMode::Ingest,
            "localhost:1491",
            "SecretPassword",
        )?;

        let bucket_count = ingest_channel.bucket_count("search")?;
        dbg!(bucket_count);
        # Ok(())
        # }
        ```
        "#]
        use CountCommand for fn bucket_count<'a>(
            collection: &'a str,
        ) where mode is ChannelMode::Ingest;

        #[doc=r#"
        Object count of bucket in indexed search data.

        Note: This method requires enabling the `ingest` feature and start 
        connection in Ingest mode.

        ```rust,no_run
        # use sonic_channel::*;
        # fn main() -> result::Result<()> {
        let ingest_channel = SonicChannel::connect_with_start(
            ChannelMode::Ingest,
            "localhost:1491",
            "SecretPassword",
        )?;

        let object_count = ingest_channel.object_count("search", "default")?;
        dbg!(object_count);
        # Ok(())
        # }
        ```
        "#]
        use CountCommand for fn object_count<'a>(
            collection: &'a str,
            bucket: &'a str => Some(bucket),
        ) where mode is ChannelMode::Ingest;

        #[doc=r#"
        Object word count in indexed bucket search data.

        Note: This method requires enabling the `ingest` feature and start 
        connection in Ingest mode.

        ```rust,no_run
        # use sonic_channel::*;
        # fn main() -> result::Result<()> {
        let ingest_channel = SonicChannel::connect_with_start(
            ChannelMode::Ingest,
            "localhost:1491",
            "SecretPassword",
        )?;

        let word_count = ingest_channel.word_count("search", "default", "recipe:296")?;
        dbg!(word_count);
        # Ok(())
        # }
        ```
        "#]
        use CountCommand for fn word_count<'a>(
            collection: &'a str,
            bucket: &'a str => Some(bucket),
            object: &'a str => Some(object),
        ) where mode is ChannelMode::Ingest;
    }

    #[cfg(feature = "search")]
    init_commands! {
        #[doc=r#"
        Query objects in database.

        Note: This method requires enabling the `search` feature and start 
        connection in Search mode.

        ```rust,no_run
        # use sonic_channel::*;
        # fn main() -> result::Result<()> {
        let search_channel = SonicChannel::connect_with_start(
            ChannelMode::Search,
            "localhost:1491",
            "SecretPassword",
        )?;

        let result = search_channel.query("search", "default", "Beef")?;
        dbg!(result);
        # Ok(())
        # }
        ```
        "#]
        use QueryCommand for fn query<'a>(
            collection: &'a str,
            bucket: &'a str,
            terms: &'a str,
        ) where mode is ChannelMode::Search;

        #[doc=r#"
        Query limited objects in database. This method similar query but
        you can configure limit of result.

        Note: This method requires enabling the `search` feature and start 
        connection in Search mode.

        ```rust,no_run
        # use sonic_channel::*;
        # fn main() -> result::Result<()> {
        let search_channel = SonicChannel::connect_with_start(
            ChannelMode::Search,
            "localhost:1491",
            "SecretPassword",
        )?;

        let result = search_channel.query_with_limit(
            "search",
            "default",
            "Beef",
            10,
        )?;
        dbg!(result);
        # Ok(())
        # }
        ```
        "#]
        use QueryCommand for fn query_with_limit<'a>(
            collection: &'a str,
            bucket: &'a str,
            terms: &'a str,
            limit: usize => Some(limit),
        ) where mode is ChannelMode::Search;

        #[doc=r#"
        Query limited objects in database. This method similar 
        query_with_limit but you can put offset in your query.

        Note: This method requires enabling the `search` feature and start 
        connection in Search mode.

        ```rust,no_run
        # use sonic_channel::*;
        # fn main() -> result::Result<()> {
        let search_channel = SonicChannel::connect_with_start(
            ChannelMode::Search,
            "localhost:1491",
            "SecretPassword",
        )?;

        let result = search_channel.query_with_limit_and_offset(
            "search",
            "default",
            "Beef",
            10,
            10,
        )?;
        dbg!(result);
        # Ok(())
        # }
        ```
        "#]
        use QueryCommand for fn query_with_limit_and_offset<'a>(
            collection: &'a str,
            bucket: &'a str,
            terms: &'a str,
            limit: usize => Some(limit),
            offset: usize => Some(offset),
        ) where mode is ChannelMode::Search;

        #[doc=r#"
        Suggest auto-completes words.

        Note: This method requires enabling the `search` feature and start 
        connection in Search mode.

        ```rust,no_run
        # use sonic_channel::*;
        # fn main() -> result::Result<()> {
        let search_channel = SonicChannel::connect_with_start(
            ChannelMode::Search,
            "localhost:1491",
            "SecretPassword",
        )?;

        let result = search_channel.suggest("search", "default", "Beef")?;
        dbg!(result);
        # Ok(())
        # }
        ```
        "#]
        use SuggestCommand for fn suggest<'a>(
            collection: &'a str,
            bucket: &'a str,
            word: &'a str,
        ) where mode is ChannelMode::Search;

        #[doc=r#"
        Suggest auto-completes words with limit.

        Note: This method requires enabling the `search` feature and start 
        connection in Search mode.

        ```rust,no_run
        # use sonic_channel::*;
        # fn main() -> result::Result<()> {
        let search_channel = SonicChannel::connect_with_start(
            ChannelMode::Search,
            "localhost:1491",
            "SecretPassword",
        )?;

        let result = search_channel.suggest_with_limit("search", "default", "Beef", 5)?;
        dbg!(result);
        # Ok(())
        # }
        ```
        "#]
        use SuggestCommand for fn suggest_with_limit<'a>(
            collection: &'a str,
            bucket: &'a str,
            word: &'a str,
            limit: usize => Some(limit),
        ) where mode is ChannelMode::Search;
    }

    #[cfg(feature = "control")]
    init_commands! {
        #[doc=r#"
        Consolidate indexed search data instead of waiting for the next automated
        consolidation tick.

        Note: This method requires enabling the `control` feature and start 
        connection in Control mode.

        ```rust,no_run
        # use sonic_channel::*;
        # fn main() -> result::Result<()> {
        let control_channel = SonicChannel::connect_with_start(
            ChannelMode::Control,
            "localhost:1491",
            "SecretPassword",
        )?;

        let result = control_channel.consolidate()?;
        assert_eq!(result, true);
        # Ok(())
        # }
        ```
        "#]
        use TriggerCommand for fn consolidate()
            where mode is ChannelMode::Control;

        #[doc=r#"
        Backup KV + FST to <path>/<BACKUP_{KV/FST}_PATH>
        See [sonic backend source code](https://github.com/valeriansaliou/sonic/blob/master/src/channel/command.rs#L808)
        for more information.

        Note: This method requires enabling the `control` feature and start 
        connection in Control mode.

        ```rust,no_run
        # use sonic_channel::*;
        # fn main() -> result::Result<()> {
        let control_channel = SonicChannel::connect_with_start(
            ChannelMode::Control,
            "localhost:1491",
            "SecretPassword",
        )?;

        let result = control_channel.backup("2020-08-07T23-48")?;
        assert_eq!(result, true);
        # Ok(())
        # }
        ```
        "#]
        use TriggerCommand for fn backup<'a>(
            // It's not action, but my macro cannot support alias for custom argument.
            // TODO: Add alias to macro and rename argument of this function.
            action: &'a str => TriggerAction::Backup(action),
        ) where mode is ChannelMode::Control;

        #[doc=r#"
        Restore KV + FST from <path> if you already have backup with the same name.

        Note: This method requires enabling the `control` feature and start 
        connection in Control mode.

        ```rust,no_run
        # use sonic_channel::*;
        # fn main() -> result::Result<()> {
        let control_channel = SonicChannel::connect_with_start(
            ChannelMode::Control,
            "localhost:1491",
            "SecretPassword",
        )?;

        let result = control_channel.restore("2020-08-07T23-48")?;
        assert_eq!(result, true);
        # Ok(())
        # }
        ```
        "#]
        use TriggerCommand for fn restore<'a>(
            // It's not action, but my macro cannot support alias for custom argument.
            // TODO: Add alias to macro and rename argument of this function.
            action: &'a str => TriggerAction::Restore(action),
        ) where mode is ChannelMode::Control;
    }
}