tarantool 11.0.0

Tarantool rust bindings
Documentation
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
use std::io::{self, Cursor, Read, Seek, Write};
use std::os::raw::c_char;

use crate::auth::AuthMethod;
use crate::error::Error;
use crate::error::TarantoolError;
use crate::index::IteratorType;
use crate::msgpack;
use crate::network::protocol::ProtocolError;
use crate::tuple::{ToTupleBuffer, Tuple};

use super::SyncIndex;

const MP_STR_MAX_HEADER_SIZE: usize = 5;

/// Keys of the HEADER and BODY maps in the iproto packets.
///
/// See `enum iproto_key` in \<tarantool>/src/box/iproto_constants.h for source
/// of truth.
pub mod iproto_key {
    pub const REQUEST_TYPE: u8 = 0x00;
    pub const SYNC: u8 = 0x01;
    // ...
    pub const SCHEMA_VERSION: u8 = 0x05;
    // ...
    pub const SPACE_ID: u8 = 0x10;
    pub const INDEX_ID: u8 = 0x11;
    pub const LIMIT: u8 = 0x12;
    pub const OFFSET: u8 = 0x13;
    pub const ITERATOR: u8 = 0x14;
    pub const INDEX_BASE: u8 = 0x15;
    // ...
    pub const KEY: u8 = 0x20;
    pub const TUPLE: u8 = 0x21;
    pub const FUNCTION_NAME: u8 = 0x22;
    pub const USER_NAME: u8 = 0x23;
    // ...
    pub const EXPR: u8 = 0x27;
    pub const OPS: u8 = 0x28;
    // ...
    pub const DATA: u8 = 0x30;
    pub const ERROR: u8 = 0x31;
    // ...
    pub const SQL_TEXT: u8 = 0x40;
    pub const SQL_BIND: u8 = 0x41;
    pub const SQL_INFO: u8 = 0x42;
    // ...
    pub const STMT_ID: u8 = 0x43;
    // ...
    pub const ERROR_EXT: u8 = 0x52;
    // ...
    pub const CLUSTER_UUID: u8 = 0x5c;
}
use iproto_key::*;

crate::define_enum_with_introspection! {
    /// Iproto packet type.
    ///
    /// See `enum iproto_type` in \<tarantool>/src/box/iproto_constants.h for source
    /// of truth.
    #[non_exhaustive]
    #[repr(C)]
    pub enum IProtoType {
        /// This packet is a response with status success.
        Ok = 0,
        Select = 1,
        Insert = 2,
        Replace = 3,
        Update = 4,
        Delete = 5,
        /// Deprecated in Tarantool 1.6 with name `IPROTO_CALL_16`.
        /// Superseeded by `IPROTO_CALL`, see [`IProtoType::Call`].
        LegacyCall = 6,
        Auth = 7,
        Eval = 8,
        Upsert = 9,
        Call = 10,
        Execute = 11,
        Nop = 12,
        Prepare = 13,
        Begin = 14,
        Commit = 15,
        Rollback = 16,
        // ...
        Id = 73,
        Ping = 64,
        // ...
        /// Error marker. This value will be combined with the error code in the
        /// actual iproto response: `(IProtoType::Error | error_code)`.
        Error = 1 << 15,
    }
}

/// Encode an IPROTO request header.
#[inline(always)]
pub fn encode_header(
    stream: &mut impl Write,
    sync: SyncIndex,
    request_type: IProtoType,
) -> Result<(), Error> {
    let helper = Header {
        sync,
        iproto_type: request_type as _,
        // Not used when encoding a request
        error_code: 0,
        // Not used when encoding a request
        schema_version: 0,
    };
    helper.encode(stream)
}

/// Prepares (hashes) password with salt according to CHAP-SHA1 algorithm.
#[inline]
pub fn chap_sha1_prepare(password: impl AsRef<[u8]>, salt: &[u8; 20]) -> Vec<u8> {
    // prepare 'chap-sha1' scramble:
    // salt = base64_decode(encoded_salt);
    // step_1 = sha1(password);
    // step_2 = sha1(step_1);
    // step_3 = sha1(first_20_bytes_of_salt, step_2);
    // scramble = xor(step_1, step_3);

    use sha1::{Digest as Sha1Digest, Sha1};

    let mut hasher = Sha1::new();
    hasher.update(password);
    let mut step_1_and_scramble = hasher.finalize();

    let mut hasher = Sha1::new();
    hasher.update(step_1_and_scramble);
    let step_2 = hasher.finalize();

    let mut hasher = Sha1::new();
    hasher.update(salt);
    hasher.update(step_2);
    let step_3 = hasher.finalize();

    step_1_and_scramble
        .iter_mut()
        .zip(step_3.iter())
        .for_each(|(a, b)| *a ^= *b);

    let scramble_bytes = step_1_and_scramble.to_vec();
    debug_assert_eq!(scramble_bytes.len(), 20);
    scramble_bytes
}

/// Prepares (hashes) password with salt according to CHAP-SHA1 algorithm and encodes into MessagePack.
// TODO(kbezuglyi): password should be `impl AsRef<[u8]>`, not `&str`.
#[inline]
pub fn chap_sha1_auth_data(password: &str, salt: &[u8; 20]) -> Vec<u8> {
    let hashed_data = chap_sha1_prepare(password, salt);
    let hashed_len = hashed_data.len();

    let mut res = Vec::with_capacity(hashed_len + MP_STR_MAX_HEADER_SIZE);
    rmp::encode::write_str_len(&mut res, hashed_len as _).expect("Can't fail for a Vec");
    res.write_all(&hashed_data).expect("Can't fail for a Vec");
    res
}

/// Prepares password according to LDAP.
#[cfg(feature = "picodata")]
#[inline]
pub fn ldap_prepare(password: impl AsRef<[u8]>) -> Vec<u8> {
    password.as_ref().to_vec()
}

/// Prepares password according to LDAP and encodes into MessagePack.
/// WARNING: data is sent without any encryption, it is recommended
/// to use SSH tunnel/SSL/else to make communication secure.
// TODO(kbezuglyi): password should be `impl AsRef<[u8]>`, not `&str`.
#[cfg(feature = "picodata")]
#[inline]
pub fn ldap_auth_data(password: &str) -> Vec<u8> {
    let hashed_data = ldap_prepare(password);
    let hashed_len = hashed_data.len();

    let mut res = Vec::with_capacity(hashed_len + MP_STR_MAX_HEADER_SIZE);
    rmp::encode::write_str_len(&mut res, hashed_len as _).expect("Can't fail for a Vec");
    res.write_all(&hashed_data).expect("Can't fail for a Vec");
    res
}

/// Prepares (hashes) password with salt according to MD5.
#[cfg(feature = "picodata")]
#[inline]
pub fn md5_prepare(user: &str, password: impl AsRef<[u8]>, salt: &[u8; 4]) -> Vec<u8> {
    // recv_from_db(salt)
    // recv_from_user(name, password)
    //   shadow_pass = md5(name + password), do not add "md5" prefix
    //   client_pass = md5(shadow_pass + salt)
    //   result = encode_as_msgpack_str(client_pass)
    // send_to_db(result)

    use md5::{Digest as Md5Digest, Md5};

    let mut md5 = Md5::new();

    md5.update(password);
    md5.update(user);
    let shadow_pass = format!("{:x}", md5.finalize_reset());

    md5.update(shadow_pass);
    md5.update(salt);
    let client_pass = format!("md5{:x}", md5.finalize());

    client_pass.into_bytes()
}

/// Prepares (hashes) password with salt according to MD5 and encodes into MessagePack.
// TODO(kbezuglyi): password should be `impl AsRef<[u8]>`, not `&str`.
#[cfg(feature = "picodata")]
#[inline]
pub fn md5_auth_data(user: &str, password: &str, salt: &[u8; 4]) -> Vec<u8> {
    let hashed_data = md5_prepare(user, password, salt);
    let hashed_len = hashed_data.len();

    let mut res = Vec::with_capacity(hashed_len + MP_STR_MAX_HEADER_SIZE);
    rmp::encode::write_str_len(&mut res, hashed_len as _).expect("Can't fail for a Vec");
    res.write_all(&hashed_data).expect("Can't fail for a Vec");
    res
}

pub fn encode_auth(
    stream: &mut impl Write,
    user: &str,
    password: &str,
    salt: &[u8],
    method: AuthMethod,
) -> Result<(), Error> {
    let auth_data;
    match method {
        AuthMethod::ChapSha1 => {
            let salt = salt
                .first_chunk()
                .ok_or_else(|| std::io::Error::other("bad salt length (expect 20)"))?;
            auth_data = chap_sha1_auth_data(password, salt);
        }
        #[cfg(feature = "picodata")]
        AuthMethod::Ldap => {
            auth_data = ldap_auth_data(password);
        }
        #[cfg(feature = "picodata")]
        AuthMethod::Md5 => {
            // We only use first four bytes of a salt. To understand why,
            // check `MD5_SALT_LEN` from `tarantool-sys/src/lib/core/md5.h:enum`,
            // that is used in `tarantool-sys/src/lib/core/crypt.c:md5_encrypt`.
            let salt = salt
                .first_chunk()
                .ok_or_else(|| std::io::Error::other("bad salt length (expect >= 4)"))?;
            auth_data = md5_auth_data(user, password, salt);
        }
        #[cfg(feature = "picodata")]
        AuthMethod::ScramSha256 => {
            use crate::error::{BoxError, TarantoolErrorCode};

            return Err(BoxError::new(
                TarantoolErrorCode::UnknownAuthMethod,
                "scram-sha256 over iproto is not supported",
            )
            .into());
        }
    }

    rmp::encode::write_map_len(stream, 2)?;

    // username:
    rmp::encode::write_pfix(stream, USER_NAME)?;
    rmp::encode::write_str(stream, user)?;

    // encrypted password:
    rmp::encode::write_pfix(stream, TUPLE)?;
    rmp::encode::write_array_len(stream, 2)?;
    rmp::encode::write_str(stream, method.as_str())?;
    stream.write_all(&auth_data)?;
    Ok(())
}

pub fn encode_ping(stream: &mut impl Write) -> Result<(), Error> {
    rmp::encode::write_map_len(stream, 0)?;
    Ok(())
}

pub fn encode_id(stream: &mut impl Write, cluster_uuid: Option<&str>) -> Result<(), Error> {
    use iproto_key::CLUSTER_UUID;

    if let Some(uuid) = cluster_uuid {
        rmp::encode::write_map_len(stream, 1)?;
        rmp::encode::write_pfix(stream, CLUSTER_UUID)?;
        rmp::encode::write_str(stream, uuid)?;
    } else {
        rmp::encode::write_map_len(stream, 0)?;
    }
    Ok(())
}

pub fn encode_execute<P>(stream: &mut impl Write, sql: &str, bind_params: &P) -> Result<(), Error>
where
    P: ToTupleBuffer + ?Sized,
{
    rmp::encode::write_map_len(stream, 2)?;
    rmp::encode::write_pfix(stream, SQL_TEXT)?;
    rmp::encode::write_str(stream, sql)?;

    rmp::encode::write_pfix(stream, SQL_BIND)?;
    bind_params.write_tuple_data(stream)?;
    Ok(())
}

pub fn encode_call<T>(stream: &mut impl Write, function_name: &str, args: &T) -> Result<(), Error>
where
    T: ToTupleBuffer + ?Sized,
{
    rmp::encode::write_map_len(stream, 2)?;
    rmp::encode::write_pfix(stream, FUNCTION_NAME)?;
    rmp::encode::write_str(stream, function_name)?;
    rmp::encode::write_pfix(stream, TUPLE)?;
    args.write_tuple_data(stream)?;
    Ok(())
}

pub fn encode_eval<T>(stream: &mut impl Write, expression: &str, args: &T) -> Result<(), Error>
where
    T: ToTupleBuffer + ?Sized,
{
    rmp::encode::write_map_len(stream, 2)?;
    rmp::encode::write_pfix(stream, EXPR)?;
    rmp::encode::write_str(stream, expression)?;
    rmp::encode::write_pfix(stream, TUPLE)?;
    args.write_tuple_data(stream)?;
    Ok(())
}

#[allow(clippy::too_many_arguments)]
pub fn encode_select<K>(
    stream: &mut impl Write,
    space_id: u32,
    index_id: u32,
    limit: u32,
    offset: u32,
    iterator_type: IteratorType,
    key: &K,
) -> Result<(), Error>
where
    K: ToTupleBuffer + ?Sized,
{
    rmp::encode::write_map_len(stream, 6)?;
    rmp::encode::write_pfix(stream, SPACE_ID)?;
    rmp::encode::write_u32(stream, space_id)?;
    rmp::encode::write_pfix(stream, INDEX_ID)?;
    rmp::encode::write_u32(stream, index_id)?;
    rmp::encode::write_pfix(stream, LIMIT)?;
    rmp::encode::write_u32(stream, limit)?;
    rmp::encode::write_pfix(stream, OFFSET)?;
    rmp::encode::write_u32(stream, offset)?;
    rmp::encode::write_pfix(stream, ITERATOR)?;
    rmp::encode::write_u32(stream, iterator_type as u32)?;
    rmp::encode::write_pfix(stream, KEY)?;
    key.write_tuple_data(stream)?;
    Ok(())
}

pub fn encode_insert<T>(stream: &mut impl Write, space_id: u32, value: &T) -> Result<(), Error>
where
    T: ToTupleBuffer + ?Sized,
{
    rmp::encode::write_map_len(stream, 2)?;
    rmp::encode::write_pfix(stream, SPACE_ID)?;
    rmp::encode::write_u32(stream, space_id)?;
    rmp::encode::write_pfix(stream, TUPLE)?;
    value.write_tuple_data(stream)?;
    Ok(())
}

pub fn encode_replace<T>(stream: &mut impl Write, space_id: u32, value: &T) -> Result<(), Error>
where
    T: ToTupleBuffer + ?Sized,
{
    rmp::encode::write_map_len(stream, 2)?;
    rmp::encode::write_pfix(stream, SPACE_ID)?;
    rmp::encode::write_u32(stream, space_id)?;
    rmp::encode::write_pfix(stream, TUPLE)?;
    value.write_tuple_data(stream)?;
    Ok(())
}

pub fn encode_update<K, Op>(
    stream: &mut impl Write,
    space_id: u32,
    index_id: u32,
    key: &K,
    ops: &Op,
) -> Result<(), Error>
where
    K: ToTupleBuffer + ?Sized,
    Op: ToTupleBuffer + ?Sized,
{
    rmp::encode::write_map_len(stream, 4)?;
    rmp::encode::write_pfix(stream, SPACE_ID)?;
    rmp::encode::write_u32(stream, space_id)?;
    rmp::encode::write_pfix(stream, INDEX_ID)?;
    rmp::encode::write_u32(stream, index_id)?;
    rmp::encode::write_pfix(stream, KEY)?;
    key.write_tuple_data(stream)?;
    rmp::encode::write_pfix(stream, TUPLE)?;
    ops.write_tuple_data(stream)?;
    Ok(())
}

pub fn encode_upsert<T, Op>(
    stream: &mut impl Write,
    space_id: u32,
    index_id: u32,
    value: &T,
    ops: &Op,
) -> Result<(), Error>
where
    T: ToTupleBuffer + ?Sized,
    Op: ToTupleBuffer + ?Sized,
{
    rmp::encode::write_map_len(stream, 4)?;
    rmp::encode::write_pfix(stream, SPACE_ID)?;
    rmp::encode::write_u32(stream, space_id)?;
    rmp::encode::write_pfix(stream, INDEX_BASE)?;
    rmp::encode::write_u32(stream, index_id)?;
    rmp::encode::write_pfix(stream, OPS)?;
    ops.write_tuple_data(stream)?;
    rmp::encode::write_pfix(stream, TUPLE)?;
    value.write_tuple_data(stream)?;
    Ok(())
}

pub fn encode_delete<K>(
    stream: &mut impl Write,
    space_id: u32,
    index_id: u32,
    key: &K,
) -> Result<(), Error>
where
    K: ToTupleBuffer + ?Sized,
{
    rmp::encode::write_map_len(stream, 3)?;
    rmp::encode::write_pfix(stream, SPACE_ID)?;
    rmp::encode::write_u32(stream, space_id)?;
    rmp::encode::write_pfix(stream, INDEX_ID)?;
    rmp::encode::write_u32(stream, index_id)?;
    rmp::encode::write_pfix(stream, KEY)?;
    key.write_tuple_data(stream)?;
    Ok(())
}

#[derive(Debug)]
pub struct Header {
    pub sync: SyncIndex,
    /// Type of the iproto packet.
    ///
    /// If the packet is an error response (see [`IProtoType::Error`]) then the
    /// error code is removed from it and assigned to [`Header::error_code`].
    ///
    /// This should be a value from `enum iproto_type` from tarantool sources,
    /// but it's practically impossible to keep our `IProtoType` up to date with
    /// the latest version of tarantool, so we just store it as a plain integer.
    pub iproto_type: u32,
    pub error_code: u32,
    pub schema_version: u64,
}

impl Header {
    /// Encode an IPROTO request header.
    ///
    // FIXME: bad name, this encodes a request header, hence error_code & schema_version are ignored.
    // This code will not work if we want to implement the server side of the protocol.
    pub fn encode(&self, stream: &mut impl Write) -> Result<(), Error> {
        rmp::encode::write_map_len(stream, 2)?;
        rmp::encode::write_pfix(stream, REQUEST_TYPE)?;
        rmp::encode::write_uint(stream, self.iproto_type as _)?;
        rmp::encode::write_pfix(stream, SYNC)?;
        rmp::encode::write_uint(stream, self.sync.0)?;
        Ok(())
    }

    /// This function doesn't need to exist
    #[inline(always)]
    pub fn encode_from_parts(
        stream: &mut impl Write,
        sync: SyncIndex,
        request_type: IProtoType,
    ) -> Result<(), Error> {
        encode_header(stream, sync, request_type)
    }

    /// Decode an IPROTO response header.
    ///
    // FIXME: bad name, this decodes only response headers.
    // This code will not work if we want to implement the server side of the protocol.
    pub fn decode(stream: &mut (impl Read + Seek)) -> Result<Header, Error> {
        let mut sync: Option<u64> = None;
        let mut iproto_type: Option<u32> = None;
        let mut error_code: u32 = 0;
        let mut schema_version: Option<u64> = None;

        let map_len = rmp::decode::read_map_len(stream)?;
        for _ in 0..map_len {
            let key = rmp::decode::read_pfix(stream)?;
            match key {
                REQUEST_TYPE => {
                    let r#type: u32 = rmp::decode::read_int(stream)?;

                    const IPROTO_TYPE_ERROR: u32 = IProtoType::Error as _;
                    if (r#type & IPROTO_TYPE_ERROR) != 0 {
                        iproto_type = Some(IPROTO_TYPE_ERROR);
                        error_code = r#type & !IPROTO_TYPE_ERROR;
                    } else {
                        iproto_type = Some(r#type);
                    }
                }
                SYNC => sync = Some(rmp::decode::read_int(stream)?),
                SCHEMA_VERSION => schema_version = Some(rmp::decode::read_int(stream)?),
                _ => msgpack::skip_value(stream)?,
            }
        }

        if sync.is_none() || iproto_type.is_none() || schema_version.is_none() {
            return Err(io::Error::from(io::ErrorKind::InvalidData).into());
        }

        Ok(Header {
            sync: SyncIndex(sync.unwrap()),
            iproto_type: iproto_type.unwrap(),
            error_code,
            schema_version: schema_version.unwrap(),
        })
    }
}

pub struct Response<T> {
    pub header: Header,
    pub payload: T,
}

/// Decode an IPROTO response header.
#[inline(always)]
pub fn decode_header(stream: &mut (impl Read + Seek)) -> Result<Header, Error> {
    Header::decode(stream)
}

////////////////////////////////////////////////////////////////////////////////
// error decoding
////////////////////////////////////////////////////////////////////////////////

/// Constant definitions for keys of the extended error info. Currently there's
/// only one possible key - error stack, and the value associated with it is an
/// array of error info maps. These error info maps have fields from the
/// [`error_field`] module defined below.
///
/// See enum MP_ERROR_* \<tarantool>/src/box/mp_error.cc
mod extended_error_keys {
    /// Stack of error infos.
    pub const STACK: u8 = 0;
}

/// Constant definitions for extended error info fields.
///
/// See enum MP_ERROR_* \<tarantool>/src/box/mp_error.cc
mod error_field {
    /// Error type.
    pub const TYPE: u8 = 0x00;

    /// File name from trace.
    pub const FILE: u8 = 0x01;

    /// Line from trace.
    pub const LINE: u8 = 0x02;

    /// Error message.
    pub const MESSAGE: u8 = 0x03;

    /// Errno at the moment of error creation.
    pub const ERRNO: u8 = 0x04;

    /// Error code.
    pub const CODE: u8 = 0x05;

    /// Type-specific fields stored as a map
    /// {string key = value}.
    pub const FIELDS: u8 = 0x06;
}

/// Reads a IPROTO packet from the `stream` (i.e. a msgpack map with integer keys)
pub fn decode_error(stream: &mut impl Read, header: &Header) -> Result<TarantoolError, Error> {
    let mut error = TarantoolError::default();

    let map_len = rmp::decode::read_map_len(stream)?;
    for _ in 0..map_len {
        let key = rmp::decode::read_pfix(stream)?;
        match key {
            ERROR => {
                let message = decode_string(stream)?;
                error.message = Some(message.into());
                error.code = header.error_code;
            }
            ERROR_EXT => {
                if let Some(e) = decode_extended_error(stream)? {
                    error = e;
                } else {
                    crate::say_verbose!("empty ERROR_EXT field");
                }
            }
            _ => {
                crate::say_verbose!("unhandled iproto key {key} when decoding error");
            }
        }
    }

    if error.message.is_none() {
        return Err(ProtocolError::ResponseFieldNotFound {
            key: "ERROR",
            context: "required for error responses",
        }
        .into());
    }

    Ok(error)
}

pub fn decode_extended_error(stream: &mut impl Read) -> Result<Option<TarantoolError>, Error> {
    let extended_error_n_fields = rmp::decode::read_map_len(stream)? as usize;
    if extended_error_n_fields == 0 {
        return Ok(None);
    }

    let mut error_info = None;

    for _ in 0..extended_error_n_fields {
        let key = rmp::decode::read_pfix(stream)?;
        match key {
            extended_error_keys::STACK => {
                if error_info.is_some() {
                    crate::say_verbose!("duplicate error stack in response");
                }

                let error_stack_len = rmp::decode::read_array_len(stream)? as usize;
                if error_stack_len == 0 {
                    continue;
                }

                let mut stack_nodes = Vec::with_capacity(error_stack_len);
                for _ in 0..error_stack_len {
                    stack_nodes.push(decode_error_stack_node(stream)?);
                }

                for mut node in stack_nodes.into_iter().rev() {
                    if let Some(next_node) = error_info {
                        node.cause = Some(Box::new(next_node));
                    }
                    error_info = Some(node);
                }
            }
            _ => {
                crate::say_verbose!("unknown extended error key {key}");
            }
        }
    }

    Ok(error_info)
}

pub fn decode_error_stack_node(mut stream: &mut impl Read) -> Result<TarantoolError, Error> {
    let mut res = TarantoolError::default();

    let map_len = rmp::decode::read_map_len(stream)? as usize;
    for _ in 0..map_len {
        let key = rmp::decode::read_pfix(stream)?;
        match key {
            error_field::TYPE => {
                res.error_type = Some(decode_string(stream)?.into_boxed_str());
            }
            error_field::FILE => {
                res.file = Some(decode_string(stream)?.into_boxed_str());
            }
            error_field::LINE => {
                res.line = Some(rmp::decode::read_int(stream)?);
            }
            error_field::MESSAGE => {
                res.message = Some(decode_string(stream)?.into_boxed_str());
            }
            error_field::ERRNO => {
                let n = rmp::decode::read_int(stream)?;
                if n != 0 {
                    res.errno = Some(n);
                }
            }
            error_field::CODE => {
                res.code = rmp::decode::read_int(stream)?;
            }
            error_field::FIELDS => match rmp_serde::from_read(&mut stream) {
                Ok(f) => {
                    res.fields = f;
                }
                Err(e) => {
                    crate::say_verbose!("failed decoding error fields: {e}");
                }
            },
            _ => {
                crate::say_verbose!("unexpected error field {key}");
            }
        }
    }

    Ok(res)
}

////////////////////////////////////////////////////////////////////////////////
// ...
////////////////////////////////////////////////////////////////////////////////

pub fn decode_string(stream: &mut impl Read) -> Result<String, Error> {
    let len = rmp::decode::read_str_len(stream)? as usize;
    let mut str_buf = vec![0u8; len];
    stream.read_exact(&mut str_buf)?;
    let res = String::from_utf8(str_buf)?;
    Ok(res)
}

pub fn decode_greeting(stream: &mut impl Read) -> Result<Vec<u8>, Error> {
    let mut buf = [0; 128];
    stream.read_exact(&mut buf)?;
    let salt = base64::decode(&buf[64..108]).unwrap();
    Ok(salt)
}

pub fn decode_call(buffer: &mut Cursor<Vec<u8>>) -> Result<Tuple, Error> {
    let payload_len = rmp::decode::read_map_len(buffer)?;
    for _ in 0..payload_len {
        let key = rmp::decode::read_pfix(buffer)?;
        match key {
            DATA => {
                return decode_tuple(buffer);
            }
            _ => {
                msgpack::skip_value(buffer)?;
            }
        };
    }
    Err(ProtocolError::ResponseFieldNotFound {
        key: "DATA",
        context: "required for CALL/EVAL responses",
    }
    .into())
}

pub fn decode_multiple_rows(buffer: &mut Cursor<Vec<u8>>) -> Result<Vec<Tuple>, Error> {
    let payload_len = rmp::decode::read_map_len(buffer)?;
    for _ in 0..payload_len {
        let key = rmp::decode::read_pfix(buffer)?;
        match key {
            DATA => {
                let items_count = rmp::decode::read_array_len(buffer)? as usize;
                let mut result = Vec::with_capacity(items_count);
                for _ in 0..items_count {
                    result.push(decode_tuple(buffer)?);
                }
                return Ok(result);
            }
            _ => {
                msgpack::skip_value(buffer)?;
            }
        };
    }
    Ok(vec![])
}

pub fn decode_single_row(buffer: &mut Cursor<Vec<u8>>) -> Result<Option<Tuple>, Error> {
    let payload_len = rmp::decode::read_map_len(buffer)?;
    for _ in 0..payload_len {
        let key = rmp::decode::read_pfix(buffer)?;
        match key {
            DATA => {
                let items_count = rmp::decode::read_array_len(buffer)? as usize;
                return Ok(if items_count == 0 {
                    None
                } else {
                    Some(decode_tuple(buffer)?)
                });
            }
            _ => {
                msgpack::skip_value(buffer)?;
            }
        }
    }
    Ok(None)
}

pub fn decode_tuple(buffer: &mut Cursor<Vec<u8>>) -> Result<Tuple, Error> {
    let payload_offset = buffer.position();
    msgpack::skip_value(buffer)?;
    let payload_len = buffer.position() - payload_offset;
    let buf = buffer.get_mut();
    unsafe {
        Ok(Tuple::from_raw_data(
            buf.as_slice().as_ptr().add(payload_offset as usize) as *mut c_char,
            payload_len as u32,
        ))
    }
}

pub fn value_slice(cursor: &mut Cursor<impl AsRef<[u8]>>) -> crate::Result<&[u8]> {
    let start = cursor.position() as usize;
    msgpack::skip_value(cursor)?;
    Ok(&cursor.get_ref().as_ref()[start..(cursor.position() as usize)])
}