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
//! Vinyl is
//!
//!
//! ```no_run
//! use embly::Future;
//! use failure::Error;
//! use vinyl_embly::query::field;
//! use vinyl_embly::DB;
//!
//! use vinyl_core::proto::example::{Color, Flower, Order};
//!
//! fn main() -> Result<(), Error> {
//!     let db = DB::new("flowers")?;
//!
//!     let mut order = Order::new();
//!     order.order_id = 2;
//!     order.price = 20;
//!
//!     let mut flower = Flower::new();
//!     flower.field_type = String::from("ROSE");
//!     flower.color = Color::RED;
//!
//!     order.set_flower(flower);
//!     db.insert(order)?.wait()?;
//!
//!     let orders: Vec<Order> = db
//!         .execute_query(
//!             field("price").less_than(50) &
//!             field("flower").matches(field("type").equals("ROSE")),
//!         )?
//!         .wait()?;
//!
//!     db.delete_record::<Order, i32>(2)?.wait()?;
//!
//!     Ok(())
//! }
//!```

#![deny(
    missing_docs,
    trivial_numeric_casts,
    unstable_features,
    unused_extern_crates,
    unused_features
)]
#![warn(unused_import_braces, unused_parens)]
#![cfg_attr(feature = "clippy", plugin(clippy(conf_file = "../../clippy.toml")))]
#![cfg_attr(
    feature = "cargo-clippy",
    allow(clippy::new_without_default, clippy::new_without_default)
)]
#![cfg_attr(
    feature = "cargo-clippy",
    warn(
        clippy::float_arithmetic,
        clippy::mut_mut,
        clippy::nonminimal_bool,
        clippy::option_map_unwrap_or,
        clippy::option_map_unwrap_or_else,
        clippy::unicode_not_nfc,
        clippy::use_self
    )
)]

pub use vinyl_core::query;
pub use vinyl_core::DefaultValue;
pub use vinyl_core::ToValue;

use embly::{spawn_function, Conn, Future};
use failure::{err_msg, Error};
use protobuf::{parse_from_bytes, Message};
use std::io::Read;
use std::io::Write;
use std::marker::PhantomData;
use std::str;
use vinyl_core::proto::transport::{Request, Response};

fn as_u32_le(array: &[u8]) -> u32 {
    u32::from(array[0])
        | (u32::from(array[1]) << 8)
        | (u32::from(array[2]) << 16)
        | (u32::from(array[3]) << 24)
}

struct ProtoResponseFuture {
    conn: Conn,
}

impl Future for ProtoResponseFuture {
    type Error = Error;
    type Item = Response;

    fn id(&self) -> i32 {
        self.conn.id()
    }
    fn fetch_result(&mut self) -> Result<Response, Error> {
        let mut size_bytes: [u8; 4] = [0; 4];
        self.conn.read_exact(&mut size_bytes)?;
        let size = as_u32_le(&size_bytes) as usize;
        let mut read = 0;
        let mut msg_bytes = vec![0; size];
        loop {
            let ln = self.conn.read(&mut msg_bytes[read..])?;
            read += ln;
            println!(
                "reading msg {:?}",
                (ln, msg_bytes[read..].len(), read, size)
            );
            if ln == 0 || read == size {
                break;
            }
        }
        let mut response: Response = parse_from_bytes(&msg_bytes)?;
        // response
        let err = response.take_error();
        if !err.is_empty() {
            Err(err_msg(err))
        } else {
            Ok(response)
        }
    }
}

/// a future that returns records
pub struct RecordsFuture<T> {
    response: ProtoResponseFuture,
    phantom: PhantomData<T>,
}

impl<T: Message> Future for RecordsFuture<T> {
    type Error = Error;
    type Item = Vec<T>;

    fn id(&self) -> i32 {
        self.response.id()
    }

    fn fetch_result(&mut self) -> Result<Vec<T>, Error> {
        let resp = self.response.wait()?;
        let mut v: Vec<T> = Vec::new();
        for record in resp.get_records().iter() {
            v.push(parse_from_bytes(record).unwrap());
        }
        Ok(v)
    }
}

/// record future
pub struct RecordFuture<T> {
    response: ProtoResponseFuture,
    record: T,
}

impl<T: Message> Future for RecordFuture<T> {
    type Error = Error;
    type Item = T;

    fn id(&self) -> i32 {
        self.response.id()
    }
    fn fetch_result(&mut self) -> Result<T, Error> {
        self.response.wait()?;
        Ok(::std::mem::replace(&mut self.record, T::new()))
    }
}

/// a future for an empty response
pub struct ResponseFuture {
    response: ProtoResponseFuture,
}

impl Future for ResponseFuture {
    type Error = Error;
    type Item = ();

    fn id(&self) -> i32 {
        self.response.id()
    }
    fn fetch_result(&mut self) -> Result<(), Error> {
        self.response.wait()?;
        Ok(())
    }
}

/// the db
pub struct DB {
    name: String,
    session_token: String,
}

impl DB {
    /// make a new one
    pub fn new(name: &str) -> Result<Self, Error> {
        let mut conn = spawn_function(&format!("embly/vinyl/{}/connect", name))?;
        conn.wait()?;
        let mut buf = Vec::new();
        conn.read_to_end(&mut buf)?;
        Ok(Self {
            name: name.to_string(),
            session_token: String::from(str::from_utf8(&buf)?),
        })
    }

    /// return records that match the provided query
    pub fn execute_query<T: Message>(&self, q: query::Query) -> Result<RecordsFuture<T>, Error> {
        let req = vinyl_core::execute_query_request::<T>(q);
        let response = self.send_request(req)?;
        Ok(RecordsFuture {
            response,
            phantom: PhantomData,
        })
    }

    /// asdf
    pub fn insert<T: Message>(&self, msg: T) -> Result<RecordFuture<T>, Error> {
        let (msg, req) = vinyl_core::insert_request::<T>(msg)?;
        let response = self.send_request(req)?;
        Ok(RecordFuture {
            response,
            record: msg,
        })
    }

    /// delete records that match the provided query
    pub fn delete_record<T: protobuf::Message, K: ToValue>(
        &self,
        pk: K,
    ) -> Result<ResponseFuture, Error> {
        let req = vinyl_core::delete_record::<T, K>(pk);
        let resp = self.send_request(req)?;
        Ok(ResponseFuture { response: resp })
    }

    fn send_request(&self, mut req: Request) -> Result<ProtoResponseFuture, Error> {
        let mut conn = spawn_function(&format!("embly/vinyl/{}", self.name))?;
        req.set_token(self.session_token.clone());
        conn.write_all(&req.write_to_bytes()?)?;
        Ok(ProtoResponseFuture { conn: conn })
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        assert_eq!(2 + 2, 4);
    }
}