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
#[macro_use]
extern crate failure;
extern crate futures;
extern crate futures_cpupool;
extern crate grpc;
extern crate httpbis;
extern crate protobuf;
extern crate serde;
extern crate serde_json;


use failure::Error;

use crate::protos::{api, api_grpc::{self, Dgraph}};

pub mod protos;

pub struct Transaction<'a> {
    context: api::TxnContext,
    finished: bool,
    read_only: bool,
    mutated: bool,
    client: &'a api_grpc::DgraphClient,
}

impl<'a> Transaction<'a> {

    pub fn query(&mut self, query: impl Into<String>) -> Result<api::Response, Error> {

        if self.finished {
            bail!("Transaction is completed");
        }

        let res = self.client.query(Default::default(),
                               api::Request {
                                   query: query.into(),
                                   ..Default::default()
                               }
        ).wait()?;

        let txn = match res.1.txn.as_ref() {
            Some(txn) => txn,
            None => bail!("Got empty transaction response back from query")
        };

        self.merge_context(txn)?;
        Ok(res.1)
    }

    pub fn mutate(&mut self, mut mu: api::Mutation) -> Result<api::Assigned, Error> {

        match (self.finished, self.read_only) {
            (true, _) => bail!("Transaction is finished"),
            (_, true) => bail!("Transaction is read only"),
            _ => ()
        }

        self.mutated = true;
        mu.start_ts = self.context.start_ts;
        let commit_now = mu.commit_now;
        let mu_res = self.client.mutate(
            Default::default(),
            mu
        ).wait();

        let mu_res = match mu_res {
            Ok(mu_res) => mu_res,
            Err(e) => {
                let _ = self.discard();
                bail!(e);
            }
        };

        if commit_now {
            self.finished = true;
        }

        let context = match mu_res.1.context.as_ref() {
            Some(context) => context,
            None => bail!("Missing transaction context on mutation response")
        };

        self.merge_context(context)?;
        Ok(mu_res.1)
    }

    pub fn commit(mut self) -> Result<(), Error> {
        match (self.finished, self.read_only) {
            (true, _) => bail!("Transaction is finished"),
            (_, true) => bail!("Transaction is read only"),
            _ => ()
        }

        self.finished = true;

        if !self.mutated {
            return Ok(())
        }


        self.client.commit_or_abort(Default::default(), self.context.clone())
            .wait()?;

        Ok(())
    }

    fn discard(&mut self) -> Result<(), Error> {
        if self.finished {
            return Ok(())
        }

        self.finished = true;

        if !self.mutated {
            return Ok(())
        }

        self.context.aborted = true;

        self.client.commit_or_abort(Default::default(), self.context.clone())
            .wait()?;

        Ok(())
    }

    fn merge_context(&mut self, src: &api::TxnContext) -> Result<(), Error> {
        if self.context.start_ts == 0 {
            self.context.start_ts = src.start_ts;
        }

        if self.context.start_ts != src.start_ts {
            bail!("self.context.start_ts != src.start_ts")
        }

        for key in src.keys.iter() {
            self.context.keys.push(key.clone());
        }

        for pred in src.preds.iter() {
            self.context.preds.push(pred.clone());
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Arc;

    use grpc::{Client, ClientStub};
    use grpc::ClientConf;
    use std::collections::HashMap;

    #[test]
    fn insert_query() -> Result<(), Error> {
        let addr = "localhost";
        let port = 9080;

        let client = api_grpc::DgraphClient::with_client(
            Arc::new(
                Client::new_plain(addr.as_ref(), port, ClientConf {
                    ..Default::default()
                })?
            )
        );

        client.alter(
            Default::default(),
            api::Operation {
                drop_all: true,
                ..Default::default()
            }
        ).wait()?;

        client.alter(
            Default::default(),
            api::Operation {
                schema: "key: string @upsert @index(hash) .".into(),
                ..Default::default()
            }
        ).wait()?;


        client.mutate(
            Default::default(),
            api::Mutation {
                set_json: r#"[{"key": "1234"}, {"key": "4567"}]"#.into(),
                commit_now: true,
                ..Default::default()
            }
        ).wait()?;


        let query = r#"
            {
                q1(func: eq(key, "1234")) {
                    uid,
                },
                q2(func: eq(key, "4567")) {
                    uid,
                }
            }
            "#;

        let res = client.query(Default::default(),
            api::Request {
                query: query.into(),
                ..Default::default()
            }
        ).wait()?;

        let json_res: HashMap<String, serde_json::Value> = serde_json::from_slice(&res.1.json)?;

        // Assert that we get uids back for both
        &json_res["q1"][0]["uid"];
        &json_res["q2"][0]["uid"];

        // Assert that we get uids back for only those 2
        assert!(&json_res.keys().len() == &2);

        assert!(&json_res["q1"].as_array().unwrap().len() == &1);
        assert!(&json_res["q2"].as_array().unwrap().len() == &1);

        Ok(())
    }


    #[test]
    fn insert_query_txn() -> Result<(), Error> {
        let addr = "localhost";
        let port = 9080;

        let client = api_grpc::DgraphClient::with_client(
            Arc::new(
                Client::new_plain(addr.as_ref(), port, ClientConf {
                    ..Default::default()
                })?
            )
        );

        client.alter(
            Default::default(),
            api::Operation {
                drop_all: true,
                ..Default::default()
            }
        ).wait()?;

        client.alter(
            Default::default(),
            api::Operation {
                schema: "key: string @upsert @index(hash) .".into(),
                ..Default::default()
            }
        ).wait()?;



        let mut handles = vec![];
        for _ in 0..50 {
            let handle = std::thread::spawn(move || {

                let client = &api_grpc::DgraphClient::with_client(
                    Arc::new(
                        Client::new_plain(addr.as_ref(), port, ClientConf {
                            ..Default::default()
                        })?
                    )
                );

                let mut tx = Transaction {
                    context: api::TxnContext::default(),
                    finished: false,
                    read_only: false,
                    mutated: false,
                    client,
                };

                let query = r#"
                    {
                        q1(func: eq(key, "1234")) {
                            uid,
                        },
                        q2(func: eq(key, "4567")) {
                            uid,
                        }
                    }
                    "#;

                // hack for type inference
                if false {
                    bail!("impossible")
                }

                let res = tx.query(query)?;
                let json_res: HashMap<String, serde_json::Value> = serde_json::from_slice(&res.json)?;

                let uid1 = json_res.get("q1").and_then(|a| a.get(0)).and_then(|m| m.get("uid"));

                let uid2 = json_res.get("q2").and_then(|a| a.get(0)).and_then(|m| m.get("uid"));


                if let (Some(uid1), Some(uid2)) = (uid1, uid2) {
                    let update = format!(
                        r#"[{{"key": "1234", "uid": {}, "update": "true"}}, {{"key": "4567", "uid": {}, "update": "true"}}]"#,
                        uid1, uid2
                    );

                    tx.mutate(
                        api::Mutation {
                            set_json: update.into_bytes(),
                            commit_now: false,
                            ..Default::default()
                        }
                    )?;
                } else {
                    tx.mutate(
                        api::Mutation {
                            set_json: r#"[{"key": "1234"}, {"key": "4567"}]"#.into(),
                            commit_now: false,
                            ..Default::default()
                        }
                    )?;
                }

                tx.commit()?;

                Ok(())
            });
            handles.push(handle);
        }

        for handle in handles {
            let _ = handle.join();  // TODO: Ensure only transaction failures occurred
        }

        // Assert that they are created
        let query = r#"
            {
                q1(func: eq(key, "1234")) {
                    uid,
                    update
                },
                q2(func: eq(key, "4567")) {
                    uid,
                    update
                }
            }
            "#;

        let res = client.query(Default::default(),
                               api::Request {
                                   query: query.into(),
                                   ..Default::default()
                               }
        ).wait()?;

        let json_res: HashMap<String, serde_json::Value> = serde_json::from_slice(&res.1.json)?;
        println!("{:#?}", json_res);

        // Assert that we get uids back for both
        &json_res["q1"][0]["uid"];
        &json_res["q2"][0]["uid"];
        &json_res["q1"][0]["update"];
        &json_res["q2"][0]["update"];

        // Assert that we get uids back for only those 2
        assert!(&json_res.keys().len() == &2);

        assert!(&json_res["q1"].as_array().unwrap().len() == &1);
        assert!(&json_res["q2"].as_array().unwrap().len() == &1);

        Ok(())
    }
}