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
/*
This file is part of Yama.

Yama is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Yama is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Yama.  If not, see <https://www.gnu.org/licenses/>.
*/


use std::convert::TryInto;
use std::io::{Read, Write};

use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};

use crate::pile::Keyspace;

pub mod requester;
pub mod responder;

#[derive(Serialize, Deserialize, Clone)]
pub struct Request {
    id: u16,
    body: RequestBody,
}

#[derive(Serialize, Deserialize, Clone)]
pub enum RequestBody {
    Read {
        kind: Keyspace,
        key: Vec<u8>,
    },
    CheckExists {
        kind: Keyspace,
        key: Vec<u8>,
    },
    Write {
        kind: Keyspace,
        key: Vec<u8>,
        value: Vec<u8>,
    },
    Delete {
        kind: Keyspace,
        key: Vec<u8>,
    },
    List {
        kind: Keyspace,
    },
    NextBatch {
        token: u16,
    },
    Flush,
    LowLevelCheck,
}

#[derive(Serialize, Deserialize, Clone)]
pub struct Response {
    response_to: u16,
    body: ResponseBody,
}

#[derive(Serialize, Deserialize, Clone)]
pub enum ResponseBody {
    Success,
    Failed(String),
    NotExists,
    Data(Vec<u8>),
    BatchData {
        batch: Vec<Vec<u8>>,
        next_token: u16,
    },
}

pub fn read_message<R: Read + Send + 'static, D: DeserializeOwned + Send + 'static>(
    read: &mut R,
) -> anyhow::Result<D> {
    let len = read.read_u32::<BigEndian>()?;
    let mut data_vec = vec![0u8; len as usize];
    read.read_exact(&mut data_vec)?;
    Ok(serde_bare::from_slice(&data_vec)?)
}

pub fn write_message<W: Write + Send + 'static, S: Serialize + Send + 'static>(
    write: &mut W,
    message: &S,
) -> anyhow::Result<()> {
    let data_vec = serde_bare::to_vec(&message)?;
    write.write_u32::<BigEndian>(data_vec.len().try_into()?)?;
    write.write_all(&data_vec)?;
    Ok(())
}