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
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
//! A Riak client for Rust.
//!
//! This client can be used to communicate with Riak clusters to send and receive objects
//! and other information. Operations are done through the `Client` struct and there are
//! several other structs designed to build data structures for sending and receiving
//! data from a Riak cluster.
//!
//! This client uses Riak's Protocol Buffers API.
//!
//! See the Protocol Buffers API documentation for more info: https://docs.basho.com/riak/kv/latest/developing/api/protocol-buffers/
//!
//! Examples:
//!
//! Storing an object is the most fundamental operation of Riak, it can be done like the following:
//!
//! ```
//! use riak::Client;
//! use riak::object::{ObjectContent, StoreObjectReq};
//!
//! // connect to Riak and ping the server
//! let mut riak = Client::new("10.0.0.2:8087").unwrap();
//! riak.ping().unwrap();
//!
//! // prepare an object
//! let contents = ObjectContent::new("I am the night, I am Batman!".as_bytes());
//!
//! // build a request to store the object
//! let mut req = StoreObjectReq::new("superheroes", &contents);
//! req.set_key("batman");
//!
//! // store the object
//! riak.store_object(&req).unwrap();
//! ```

#[macro_use]
extern crate log;
extern crate protobuf;

pub mod bucket;
pub mod errors;
pub mod object;
pub mod preflist;
pub mod stream;
pub mod yokozuna;

mod connection;
mod private_traits;
mod rpb;

use bucket::BucketProps;
use errors::RiakError;
use connection::RiakConn;
use object::{DeleteObjectReq, FetchObjectReq, StoreObjectReq, FetchObjectResp};
use preflist::PreflistItem;
use private_traits::{BucketPropsPrivate, DeleteObjectReqPrivate, YokozunaIndexPrivate};
use protobuf::{Message, parse_from_bytes};
use rpb::codes;
use rpb::riak::{RpbGetBucketReq, RpbGetBucketResp, RpbGetBucketTypeReq, RpbGetServerInfoResp,
                RpbResetBucketReq};
use rpb::riak_kv::{RpbGetResp, RpbGetBucketKeyPreflistReq, RpbGetBucketKeyPreflistResp};
use rpb::riak_yokozuna::{RpbYokozunaSchema, RpbYokozunaSchemaPutReq, RpbYokozunaSchemaGetReq,
                         RpbYokozunaSchemaGetResp, RpbYokozunaIndexGetReq,
                         RpbYokozunaIndexGetResp, RpbYokozunaIndexDeleteReq};
use rpb::utils::{rpb_get_resp_to_fetch_object_resp, RpbGenerator};
use std::net::ToSocketAddrs;
use stream::{BucketStream, KeyStream};
use yokozuna::YokozunaIndex;

static DEFAULT_TIMEOUT: u32 = 3600;

/// `Client` Represents a connection to a Riak server's Protocol Buffers API.
#[derive(Debug)]
pub struct Client {
    connection: RiakConn,
    timeout: u32,
}

impl Client {
    /// Constructs a new `Client` with the timeout for requests with a default timeout.
    ///
    /// # Examples
    ///
    /// ```
    /// use riak::Client;
    ///
    /// let mut riak = Client::new("10.0.0.2:8087").unwrap();
    /// riak.ping().unwrap();
    /// ```
    ///
    /// # Errors
    ///
    /// TODO
    pub fn new<A: ToSocketAddrs>(addr: A) -> Result<Client, RiakError> {
        Client::new_with_timeout(addr, DEFAULT_TIMEOUT)
    }

    /// Constructs a new `Client` with a timeout (in seconds) provided.
    ///
    /// # Examples
    ///
    /// ```
    /// use riak::Client;
    ///
    /// let mut riak = Client::new_with_timeout("10.0.0.2:8087", 3600).unwrap();
    /// riak.ping().unwrap();
    /// ```
    ///
    /// # Errors
    ///
    /// TODO
    pub fn new_with_timeout<A: ToSocketAddrs>(addr: A, timeout: u32) -> Result<Client, RiakError> {
        let connection = match RiakConn::new(addr, timeout) {
            Ok(connection) => connection,
            Err(error) => return Err(error),
        };

        Ok(Client {
            connection: connection,
            timeout: timeout,
        })
    }

    /// Set the timeout (in seconds) allowed for future requests.
    ///
    /// # Examples
    ///
    /// ```
    /// use riak::Client;
    ///
    /// let mut riak = Client::new("10.0.0.2:8087").unwrap();
    /// riak.set_timeout(3600);
    /// ```
    pub fn set_timeout(&mut self, timeout: u32) {
        self.timeout = timeout;
    }

    /// Reconnect to the Riak server originally connected to when this client was initiated.
    ///
    /// # Examples
    ///
    /// ```
    /// use riak::Client;
    ///
    /// let mut riak = Client::new("10.0.0.2:8087").unwrap();
    /// riak.reconnect().unwrap();
    /// ```
    ///
    /// # Errors
    ///
    /// TODO
    pub fn reconnect(&mut self) -> Result<(), RiakError> {
        self.connection.reconnect()
    }

    /// Sends a ping message to Riak and returns a Result.
    ///
    /// # Examples
    ///
    /// ```
    /// use riak::Client;
    ///
    /// let mut riak = Client::new("10.0.0.2:8087").unwrap();
    /// riak.ping().unwrap();
    /// ```
    ///
    /// # Errors
    ///
    /// TODO
    pub fn ping(&mut self) -> Result<(), RiakError> {
        let ping_data: Vec<u8> = vec![];
        match self.connection.exchange(codes::RpbPingReq, codes::RpbPingResp, &ping_data) {
            Ok(_) => Ok(()),
            Err(err) => Err(err),
        }
    }

    /// Get the node name and server version of the Riak server reached.
    ///
    /// # Examples
    ///
    /// ```
    /// use riak::Client;
    ///
    /// let mut riak = Client::new("10.0.0.2:8087").unwrap();
    /// let (node, version) = riak.server_info().unwrap();
    ///
    /// println!("Connected to node {}, running Riak version {}", node, version);
    /// ```
    pub fn server_info(&mut self) -> Result<(String, String), RiakError> {
        // send an `RpbGetServerInfoReq` and get the response bytes
        let response = match self.connection.exchange(codes::RpbGetServerInfoReq,
                                                      codes::RpbGetServerInfoResp,
                                                      &vec![]) {
            Ok(response) => response,
            Err(error) => return Err(error),
        };

        // parse the response bytes into an `RpbGetBucketResp` struct
        let rpb_get_server_info_resp = match parse_from_bytes::<RpbGetServerInfoResp>(&response) {
            Ok(response) => response,
            Err(error) => return Err(RiakError::ProtobufError(error)),
        };

        // return the node name and server version as strings
        Ok((String::from_utf8_lossy(rpb_get_server_info_resp.get_node()).into_owned(),
            String::from_utf8_lossy(rpb_get_server_info_resp.get_server_version()).into_owned()))
    }

    /// Produces a stream of bucket names.
    ///
    /// Caution: This call can be expensive for the server. Do not use in performance-sensitive code.
    ///
    /// # Examples
    ///
    /// ```
    /// use riak::Client;
    ///
    /// let mut riak = Client::new("10.0.0.2:8087").unwrap();
    /// let mut bucketstream = riak.stream_buckets().unwrap();
    ///
    /// loop {
    ///     match bucketstream.next() {
    ///         Some(buckets) => println!("found buckets {:?}", buckets.unwrap()),
    ///         None => break,
    ///     };
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// TODO
    pub fn stream_buckets(&mut self) -> Result<BucketStream, RiakError> {
        BucketStream::new(self)
    }

    /// Produces a list of bucket names.
    ///
    /// Caution: This call can be expensive for the server. Do not use in performance-sensitive code.
    ///
    /// # Examples
    ///
    /// ```
    /// use riak::Client;
    ///
    /// let mut riak = Client::new("10.0.0.2:8087").unwrap();
    /// let buckets = riak.list_buckets().unwrap();
    ///
    /// for bucket in buckets.iter() {
    ///     println!("found bucket named {}", bucket);
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// TODO
    pub fn list_buckets(&mut self) -> Result<Vec<String>, RiakError> {
        let mut bucket_stream = match self.stream_buckets() {
            Ok(bucket_stream) => bucket_stream,
            Err(error) => return Err(error),
        };

        bucket_stream.all()
    }

    /// Sets the properties for a bucket given a bucket name.
    ///
    /// # Examples
    ///
    /// ```
    /// use riak::Client;
    /// use riak::bucket::BucketProps;
    ///
    /// let mut riak = Client::new("10.0.0.2:8087").unwrap();
    /// let mut bucket_props = BucketProps::new();
    /// bucket_props.set_backend("bitcask");
    ///
    /// riak.set_bucket_properties("superheroes", &bucket_props).unwrap();
    /// ```
    ///
    /// # Errors
    ///
    /// TODO
    pub fn set_bucket_properties(&mut self,
                                 bucket_name: &str,
                                 bucket_props: &BucketProps)
                                 -> Result<(), RiakError> {
        // convert the `BucketProps` to protobuf bytes
        let bytes = match bucket_props.write_to_bytes(bucket_name, false) {
            Ok(b) => b,
            Err(err) => return Err(err),
        };

        // make the exchange and check for any errors
        match self.connection.exchange(codes::RpbSetBucketReq, codes::RpbSetBucketResp, &bytes) {
            Ok(_) => Ok(()),
            Err(err) => Err(err),
        }
    }

    /// Retrieves bucket properties for a bucket given a bucket name.
    ///
    /// # Examples
    ///
    /// ```
    /// use riak::Client;
    ///
    /// let mut riak = Client::new("10.0.0.2:8087").unwrap();
    /// let bucket_props = riak.get_bucket_properties("superheroes").unwrap();
    /// println!("bucket properties for superheroes: {:?}", bucket_props);
    /// ```
    ///
    /// # Errors
    ///
    /// TODO
    pub fn get_bucket_properties(&mut self, bucket_name: &str) -> Result<BucketProps, RiakError> {
        // build a protobuf request
        let mut req = RpbGetBucketReq::new();
        req.set_bucket(bucket_name.to_string().into_bytes());

        // parse the protobuf request into bytes
        let bytes = match req.write_to_bytes() {
            Ok(bytes) => bytes,
            Err(error) => return Err(RiakError::ProtobufError(error)),
        };

        // make the exchange with the server and get the response bytes
        let response = match self.connection
            .exchange(codes::RpbGetBucketReq, codes::RpbGetBucketResp, &bytes) {
            Ok(response) => response,
            Err(error) => return Err(error),
        };

        // parse the response bytes into an `RpbGetBucketResp` struct
        let mut rpb_get_bucket_resp = match parse_from_bytes::<RpbGetBucketResp>(&response) {
            Ok(rpb_get_bucket_resp) => rpb_get_bucket_resp,
            Err(error) => return Err(RiakError::ProtobufError(error)),
        };

        // pull the `RpbBucketProps` out of the response to build the `BucketProps` struct
        let rpb_bucket_props = rpb_get_bucket_resp.take_props();
        let mut bucket_props = BucketProps::new();
        bucket_props.set_props(&rpb_bucket_props);

        // return the resulting `BucketProps`
        Ok(bucket_props)
    }

    /// Assigns a set of bucket properties to a bucket type.
    ///
    /// # Examples
    ///
    /// ```
    /// use riak::Client;
    /// use riak::bucket::BucketProps;
    ///
    /// let mut riak = Client::new("10.0.0.2:8087").unwrap();
    /// let mut bucket_props = BucketProps::new();
    /// bucket_props.set_backend("bitcask");
    ///
    /// riak.set_bucket_type_properties("comicbooks", &bucket_props).unwrap();
    /// ```
    ///
    /// # Errors
    ///
    /// TODO
    pub fn set_bucket_type_properties(&mut self,
                                      bucket_type_name: &str,
                                      bucket_type_props: &BucketProps)
                                      -> Result<(), RiakError> {
        // convert the `BucketProps` to protobuf bytes
        let bytes = match bucket_type_props.write_to_bytes(bucket_type_name, true) {
            Ok(b) => b,
            Err(err) => return Err(err),
        };

        // make the exchange and check for any errors
        match self.connection
            .exchange(codes::RpbSetBucketTypeReq, codes::RpbSetBucketResp, &bytes) {
            Ok(_) => Ok(()),
            Err(err) => Err(err),
        }
    }

    /// Gets the bucket properties associated with a bucket type.
    ///
    /// # Examples
    ///
    /// ```
    /// use riak::Client;
    ///
    /// let mut riak = Client::new("10.0.0.2:8087").unwrap();
    /// let props = riak.get_bucket_type_properties("comicbooks").unwrap();
    /// println!("found bucket properties for type \"comicbooks\": {:?}", props);
    /// ```
    ///
    /// # Errors
    ///
    /// TODO
    pub fn get_bucket_type_properties(&mut self,
                                      bucket_type_name: &str)
                                      -> Result<BucketProps, RiakError> {
        // build the request
        let mut req = RpbGetBucketTypeReq::new();
        req.set_field_type(bucket_type_name.to_string().into_bytes());

        // parse the request into bytes
        let bytes = match req.write_to_bytes() {
            Ok(bytes) => bytes,
            Err(error) => return Err(RiakError::ProtobufError(error)),
        };

        // make the exchange and get the response bytes
        let response = match self.connection
            .exchange(codes::RpbGetBucketTypeReq, codes::RpbGetBucketResp, &bytes) {
            Ok(response) => response,
            Err(error) => return Err(error),
        };

        // if a proper response is received, parse it into a `RpbGetBucketResp`
        let mut rpb_get_bucket_resp = match parse_from_bytes::<RpbGetBucketResp>(&response) {
            Ok(rpb_get_bucket_resp) => rpb_get_bucket_resp,
            Err(error) => return Err(RiakError::ProtobufError(error)),
        };

        // if no parsing errors occur, build a `BucketProps` to return
        let rpb_bucket_props = rpb_get_bucket_resp.take_props();
        let mut bucket_props = BucketProps::new();
        bucket_props.set_props(&rpb_bucket_props);

        // return the resulting properties
        Ok(bucket_props)
    }

    /// Resets the properties for a bucket
    ///
    /// # Examples
    ///
    /// ```
    /// use riak::Client;
    ///
    /// let mut riak = Client::new("10.0.0.2:8087").unwrap();
    /// riak.reset_bucket("default", "superheroes").unwrap();
    /// ```
    ///
    /// # Errors
    ///
    /// TODO
    pub fn reset_bucket(&mut self, bucket_type: &str, bucket: &str) -> Result<(), RiakError> {
        // build a `RpbResetBucketReq` requests
        let mut request = RpbResetBucketReq::new();
        request.set_field_type(bucket_type.to_string().into_bytes());
        request.set_bucket(bucket.to_string().into_bytes());

        // parse the request into bytes
        let bytes = match request.write_to_bytes() {
            Ok(bytes) => bytes,
            Err(error) => return Err(RiakError::ProtobufError(error)),
        };

        // make the exchange with the server, no return needed on success
        match self.connection
            .exchange(codes::RpbResetBucketReq, codes::RpbResetBucketResp, &bytes) {
            Ok(_) => Ok(()),
            Err(error) => Err(error),
        }
    }

    /// Produces a stream of keys from a bucket given a bucket name.
    ///
    /// Note: This operation requires traversing all keys stored in the cluster and should not be used in production.
    ///
    /// # Examples
    ///
    /// ```
    /// use riak::Client;
    ///
    /// let mut riak = Client::new("10.0.0.2:8087").unwrap();
    /// let mut keystream = riak.stream_keys("superheroes").unwrap();
    ///
    /// loop {
    ///     match keystream.next() {
    ///         Some(keys_result) => println!("found keys {:?}", keys_result.unwrap()),
    ///         None => break,
    ///     };
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// TODO
    pub fn stream_keys(&mut self, bucket: &str) -> Result<KeyStream, RiakError> {
        KeyStream::new(self, bucket)
    }

    /// Produces a list of keys provided a bucket name
    ///
    /// Note: This operation requires traversing all keys stored in the cluster and should not be used in production.
    ///
    /// # Examples
    ///
    /// ```
    /// use riak::Client;
    ///
    /// let mut riak = Client::new("10.0.0.2:8087").unwrap();
    /// let keys = riak.list_keys("superheroes").unwrap();
    ///
    /// for key in keys.iter() {
    ///     println!("found key in bucket superheroes named {}", key);
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// TODO
    pub fn list_keys(&mut self, bucket: &str) -> Result<Vec<String>, RiakError> {
        match KeyStream::new(self, bucket) {
            Ok(mut keys) => keys.all(),
            Err(error) => Err(error),
        }
    }

    /// Stores an object on the Riak server.
    ///
    /// # Examples
    ///
    /// ```
    /// use riak::Client;
    /// use riak::object::{ObjectContent, StoreObjectReq};
    ///
    /// let mut riak = Client::new("10.0.0.2:8087").unwrap();
    ///
    /// let contents = ObjectContent::new("I am the night, I am Batman!".as_bytes());
    /// let mut req = StoreObjectReq::new("superheroes", &contents);
    /// req.set_key("batman");
    ///
    /// riak.store_object(&req).unwrap();
    /// ```
    ///
    /// # Errors
    ///
    /// TODO
    pub fn store_object(&mut self, req: &StoreObjectReq) -> Result<(), RiakError> {
        // convert the request to protobuf bytes
        let bytes = match req.write_to_bytes() {
            Ok(b) => b,
            Err(err) => return Err(err),
        };

        // make the exchange and check for errors
        match self.connection.exchange(codes::RpbPutReq, codes::RpbPutResp, &bytes) {
            Ok(_) => Ok(()),
            Err(err) => Err(err),
        }
    }

    /// Fetches an object from the Riak server.
    ///
    /// # Examples
    ///
    /// ```
    /// use riak::Client;
    /// use riak::object::FetchObjectReq;
    ///
    /// let mut riak = Client::new("10.0.0.2:8087").unwrap();
    ///
    /// let req = FetchObjectReq::new("superheroes", "batman");
    /// let object = riak.fetch_object(&req).unwrap();
    /// println!("batman object contained: {:?}", object);
    /// ```
    ///
    /// # Errors
    ///
    /// TODO
    pub fn fetch_object(&mut self, req: &FetchObjectReq) -> Result<FetchObjectResp, RiakError> {
        // convert the request to protobuf bytes
        let bytes = match req.write_to_bytes() {
            Ok(b) => b,
            Err(err) => return Err(err),
        };

        // make the exchange and get the response bytes
        let response = match self.connection
            .exchange(codes::RpbGetReq, codes::RpbGetResp, &bytes) {
            Ok(response) => response,
            Err(error) => return Err(error),
        };

        // parse the response into an `RpbGetResp` struct
        let mut rpb_get_resp = match parse_from_bytes::<RpbGetResp>(&response) {
            Ok(rpb_get_resp) => rpb_get_resp,
            Err(err) => return Err(RiakError::ProtobufError(err)),
        };

        // if no errors occur build a `FetchObjectResp` to return
        let fetch_object_resp = rpb_get_resp_to_fetch_object_resp(&mut rpb_get_resp);
        Ok(fetch_object_resp)
    }

    /// Deletes an object from Riak
    ///
    /// # Examples
    ///
    /// ```
    /// use riak::Client;
    /// use riak::object::DeleteObjectReq;
    ///
    /// let mut riak = Client::new("10.0.0.2:8087").unwrap();
    ///
    /// let mut request = DeleteObjectReq::new("superheroes", "batman");
    /// request.set_dw(3);
    ///
    /// riak.delete_object(&request).unwrap();
    /// ```
    ///
    /// # Errors
    ///
    /// TODO
    pub fn delete_object(&mut self, request: &DeleteObjectReq) -> Result<(), RiakError> {
        // parse the request into bytes to send out
        let bytes = match request.write_to_bytes() {
            Ok(bytes) => bytes,
            Err(error) => return Err(error),
        };

        // make the exchange, nothing to return on success
        match self.connection.exchange(codes::RpbDelReq, codes::RpbDelResp, &bytes) {
            Ok(_) => Ok(()),
            Err(error) => Err(error),
        }
    }

    /// Fetch the preflist for a bucket/key combination.
    ///
    /// # Examples
    ///
    /// ```
    /// use riak::Client;
    ///
    /// let mut riak = Client::new("10.0.0.2:8087").unwrap();
    /// let preflist = riak.fetch_preflist("superheroes", "batman").unwrap();
    ///
    /// for preflist_item in preflist {
    ///     if preflist_item.is_primary {
    ///         println!("found primary partition {} for key {} on node {}", preflist_item.partition, "batman", preflist_item.node);
    ///     }
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// TODO
    pub fn fetch_preflist(&mut self,
                          bucket: &str,
                          key: &str)
                          -> Result<Vec<PreflistItem>, RiakError> {
        // build the request
        let mut req = RpbGetBucketKeyPreflistReq::new();
        req.set_bucket(bucket.to_string().into_bytes());
        req.set_key(key.to_string().into_bytes());

        // parse the request into bytes
        let bytes = match req.write_to_bytes() {
            Ok(bytes) => bytes,
            Err(error) => return Err(RiakError::ProtobufError(error)),
        };

        // send the request and check the response
        let response = match self.connection
            .exchange(codes::RpbGetBucketKeyPreflistReq,
                      codes::RpbGetBucketKeyPreflistResp,
                      &bytes) {
            Ok(response) => response,
            Err(error) => return Err(error),
        };

        // parse the response
        let rpb_preflist_resp = match parse_from_bytes::<RpbGetBucketKeyPreflistResp>(&response) {
            Ok(parsed) => parsed,
            Err(err) => return Err(RiakError::ProtobufError(err)),
        };

        // get each item and build a `PreflistItem` for it
        let mut preflist: Vec<PreflistItem> = Vec::new();
        for preflist_item in rpb_preflist_resp.get_preflist() {
            let node = String::from_utf8_lossy(preflist_item.get_node()).into_owned();
            let converted = PreflistItem::new(preflist_item.get_partition(),
                                              &node,
                                              preflist_item.get_primary());
            preflist.push(converted);
        }

        Ok(preflist)
    }

    /// Create a search schema
    ///
    /// # Examples
    ///
    /// ```
    /// use riak::Client;
    /// use std::fs::File;
    /// use std::io::Read;
    ///
    /// let mut riak = Client::new("10.0.0.2:8087").unwrap();
    ///
    /// let mut xml: Vec<u8> = Vec::new();
    /// let mut file = File::open("/tmp/riak-rust-client-default-schema.xml").unwrap();
    /// let _ = file.read_to_end(&mut xml).unwrap();
    ///
    /// riak.set_yokozuna_schema("schedule", &xml).unwrap();
    /// ```
    ///
    /// # Errors
    ///
    /// TODO
    pub fn set_yokozuna_schema(&mut self, name: &str, content: &Vec<u8>) -> Result<(), RiakError> {
        // build a `RpbYokozunaSchema`
        let mut schema = RpbYokozunaSchema::new();
        schema.set_name(name.to_string().into_bytes());
        schema.set_content(content.clone());

        // build a `RpbYokozunaSchemaPutReq` request
        let mut req = RpbYokozunaSchemaPutReq::new();
        req.set_schema(schema);

        // parse the request into bytes to send
        let bytes = match req.write_to_bytes() {
            Ok(bytes) => bytes,
            Err(error) => return Err(RiakError::ProtobufError(error)),
        };

        // make the exchange, no return needed on success
        match self.connection
            .exchange(codes::RpbYokozunaSchemaPutReq, codes::RpbPutResp, &bytes) {
            Ok(_) => Ok(()),
            Err(error) => Err(error),
        }
    }

    /// Retrieve a search schema
    ///
    /// # Examples
    ///
    /// ```
    /// use riak::Client;
    ///
    /// let mut riak = Client::new("10.0.0.2:8087").unwrap();
    /// riak.get_yokozuna_schema("schedule").unwrap();
    /// ```
    ///
    /// # Errors
    ///
    /// TODO
    pub fn get_yokozuna_schema(&mut self, name: &str) -> Result<Vec<u8>, RiakError> {
        // build a request
        let mut req = RpbYokozunaSchemaGetReq::new();
        req.set_name(name.to_string().into_bytes());

        // parse the request into bytes
        let bytes = match req.write_to_bytes() {
            Ok(bytes) => bytes,
            Err(error) => return Err(RiakError::ProtobufError(error)),
        };

        // make the exchange and get the response bytes
        let response = match self.connection.exchange(codes::RpbYokozunaSchemaGetReq,
                                                      codes::RpbYokozunaSchemaGetResp,
                                                      &bytes) {
            Ok(response) => response,
            Err(error) => return Err(error),
        };

        // parse the response into a `RpbYokozunaSchemaGetResp`
        let mut rpb_yokozuna_schema_get_resp =
            match parse_from_bytes::<RpbYokozunaSchemaGetResp>(&response) {
                Ok(parsed) => parsed,
                Err(error) => return Err(RiakError::ProtobufError(error)),
            };

        // grab the schema out of the response
        let mut rpb_yokozuna_schema = rpb_yokozuna_schema_get_resp.take_schema();

        // return the contents of the schema
        Ok(rpb_yokozuna_schema.take_content())
    }

    /// set a search index
    ///
    /// # Examples
    ///
    /// ```
    /// use riak::Client;
    /// use riak::yokozuna::YokozunaIndex;
    ///
    /// let mut riak = Client::new("10.0.0.2:8087").unwrap();
    /// let index = YokozunaIndex::new("myindex");
    ///
    /// riak.set_yokozuna_index(&index).unwrap();
    /// ```
    ///
    /// # Errors
    ///
    /// TODO
    pub fn set_yokozuna_index(&mut self, index: &YokozunaIndex) -> Result<(), RiakError> {
        let bytes = match index.write_to_bytes() {
            Ok(bytes) => bytes,
            Err(error) => return Err(error),
        };

        match self.connection.exchange(codes::RpbYokozunaIndexPutReq, codes::RpbPutResp, &bytes) {
            Ok(_) => Ok(()),
            Err(error) => Err(error),
        }
    }

    /// get a search index
    ///
    /// # Examples
    ///
    /// ```
    /// use riak::Client;
    ///
    /// let mut riak = Client::new("10.0.0.2:8087").unwrap();
    ///
    /// riak.get_yokozuna_index("myindex").unwrap();
    /// ```
    ///
    /// # Errors
    ///
    /// TODO
    pub fn get_yokozuna_index(&mut self, name: &str) -> Result<Vec<YokozunaIndex>, RiakError> {
        // build the request
        let mut req = RpbYokozunaIndexGetReq::new();
        req.set_name(name.to_string().into_bytes());

        // parse the request into bytes
        let bytes = match req.write_to_bytes() {
            Ok(bytes) => bytes,
            Err(error) => return Err(RiakError::ProtobufError(error)),
        };

        // exchange the request and get the response bytes
        let response = match self.connection.exchange(codes::RpbYokozunaIndexGetReq,
                                                      codes::RpbYokozunaIndexGetResp,
                                                      &bytes) {
            Ok(response) => response,
            Err(error) => return Err(error),
        };

        // parse the response
        let rpb_yokozuna_index_get_resp =
            match parse_from_bytes::<RpbYokozunaIndexGetResp>(&response) {
                Ok(rpb_yokozuna_index_get_resp) => rpb_yokozuna_index_get_resp,
                Err(error) => return Err(RiakError::ProtobufError(error)),
            };

        // build a Vec of all the indexes in the response and return it
        let mut indexes: Vec<YokozunaIndex> = Vec::new();
        for rpb_yokozuna_index in rpb_yokozuna_index_get_resp.get_index().iter() {
            let index = YokozunaIndex::new_from_rpb_yokozuna_index(&rpb_yokozuna_index);
            indexes.push(index);
        }
        Ok(indexes)
    }

    /// Deletes an index
    ///
    /// # Examples
    ///
    /// ```
    /// use riak::Client;
    /// use riak::yokozuna::YokozunaIndex;
    ///
    /// let mut riak = Client::new("10.0.0.2:8087").unwrap();
    /// let index = YokozunaIndex::new("deleteme");
    ///
    /// riak.set_yokozuna_index(&index).unwrap();
    /// riak.delete_yokozuna_index("deleteme").unwrap();
    /// ```
    ///
    /// # Errors
    ///
    /// TODO
    pub fn delete_yokozuna_index(&mut self, name: &str) -> Result<(), RiakError> {
        // build the request
        let mut req = RpbYokozunaIndexDeleteReq::new();
        req.set_name(name.to_string().into_bytes());

        // parse the request into bytes
        let bytes = match req.write_to_bytes() {
            Ok(bytes) => bytes,
            Err(error) => return Err(RiakError::ProtobufError(error)),
        };

        // make the exchange with the server and get the response bytes
        match self.connection
            .exchange(codes::RpbYokozunaIndexDeleteReq, codes::RpbDelResp, &bytes) {
            Ok(_) => Ok(()),
            Err(error) => Err(error),
        }
    }
}