Browse Source

Actix: upgrade postgres driver (#4637)

* upgrade postgres driver

* fix docker file name
Nikolay Kim 6 years ago
parent
commit
2e33211404

+ 1 - 1
frameworks/Rust/actix/Cargo.toml

@@ -40,7 +40,7 @@ http = "0.1"
 diesel = { version = "1.2", features = ["postgres"] }
 url = { version="1.7", features=["query_encoding"] }
 log = { version = "0.4", features = ["release_max_level_off"] }
-phf = "0.7.22"
+v_htmlescape = "0.4"
 tokio-postgres = { git="https://github.com/fafhrd91/rust-postgres.git" }
 
 [build-dependencies]

+ 0 - 0
frameworks/Rust/actix/actix-platform.dockerfile → frameworks/Rust/actix/actix-core.dockerfile


+ 2 - 2
frameworks/Rust/actix/benchmark_config.json

@@ -19,7 +19,7 @@
       "notes": "",
       "versus": ""
     },
-    "platform": {
+    "core": {
       "fortune_url": "/fortune",
       "json_url": "/json",
       "plaintext_url": "/plaintext",
@@ -37,7 +37,7 @@
       "webserver": "actix-web",
       "os": "Linux",
       "database_os": "Linux",
-      "display_name": "Actix [raw]",
+      "display_name": "Actix [Platform]",
       "notes": "",
       "versus": ""
     },

+ 15 - 9
frameworks/Rust/actix/src/db_pg.rs

@@ -4,7 +4,7 @@ use actix::fut;
 use actix::prelude::*;
 use futures::{stream, Future, Stream};
 use rand::{thread_rng, Rng, ThreadRng};
-use tokio_postgres::{connect, Client, Statement, TlsMode};
+use tokio_postgres::{connect, Client, NoTls, Statement};
 
 use crate::models::{Fortune, World};
 
@@ -22,7 +22,7 @@ impl Actor for PgConnection {
 
 impl PgConnection {
     pub fn connect(db_url: &str) -> Addr<PgConnection> {
-        let hs = connect(db_url.parse().unwrap(), TlsMode::None);
+        let hs = connect(db_url, NoTls);
 
         PgConnection::create(move |ctx| {
             let act = PgConnection {
@@ -34,7 +34,7 @@ impl PgConnection {
 
             hs.map_err(|_| panic!("can not connect to postgresql"))
                 .into_actor(&act)
-                .and_then(|(cl, conn), act, ctx| {
+                .and_then(|(mut cl, conn), act, ctx| {
                     ctx.wait(
                         cl.prepare("SELECT id, message FROM fortune")
                             .map_err(|_| ())
@@ -83,7 +83,7 @@ impl Handler<RandomWorld> for PgConnection {
                 .unwrap()
                 .query(self.world.as_ref().unwrap(), &[&random_id])
                 .into_future()
-                .map_err(|e| io::Error::new(io::ErrorKind::Other, e.0))
+                .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("{:?}", e.0)))
                 .and_then(|(row, _)| {
                     let row = row.unwrap();
                     Ok(World {
@@ -114,7 +114,9 @@ impl Handler<RandomWorlds> for PgConnection {
                     .unwrap()
                     .query(self.world.as_ref().unwrap(), &[&w_id])
                     .into_future()
-                    .map_err(|e| io::Error::new(io::ErrorKind::Other, e.0))
+                    .map_err(|e| {
+                        io::Error::new(io::ErrorKind::Other, format!("{:?}", e.0))
+                    })
                     .and_then(|(row, _)| {
                         let row = row.unwrap();
                         Ok(World {
@@ -149,7 +151,9 @@ impl Handler<UpdateWorld> for PgConnection {
                     .unwrap()
                     .query(self.world.as_ref().unwrap(), &[&w_id])
                     .into_future()
-                    .map_err(|e| io::Error::new(io::ErrorKind::Other, e.0))
+                    .map_err(|e| {
+                        io::Error::new(io::ErrorKind::Other, format!("{:?}", e.0))
+                    })
                     .and_then(move |(row, _)| {
                         let row = row.unwrap();
                         Ok(World {
@@ -181,8 +185,9 @@ impl Handler<UpdateWorld> for PgConnection {
                     act.cl
                         .as_mut()
                         .unwrap()
-                        .batch_execute(&update)
-                        .map_err(|e| io::Error::new(io::ErrorKind::Other, e))
+                        .simple_query(&update)
+                        .collect()
+                        .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("{:?}", e)))
                         .into_actor(act)
                         .and_then(|_, _, _| fut::ok(worlds))
                 }),
@@ -211,6 +216,7 @@ impl Handler<TellFortune> for PgConnection {
                 .as_mut()
                 .unwrap()
                 .query(self.fortune.as_ref().unwrap(), &[])
+                .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("{:?}", e)))
                 .fold(items, move |mut items, row| {
                     items.push(Fortune {
                         id: row.get(0),
@@ -218,7 +224,7 @@ impl Handler<TellFortune> for PgConnection {
                     });
                     Ok::<_, io::Error>(items)
                 })
-                .map_err(|e| io::Error::new(io::ErrorKind::Other, e))
+                .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("{:?}", e)))
                 .and_then(|mut items| {
                     items.sort_by(|it, next| it.message.cmp(&next.message));
                     Ok(items)

+ 21 - 11
frameworks/Rust/actix/src/db_pg_direct.rs

@@ -3,7 +3,7 @@ use std::io;
 use futures::future::join_all;
 use futures::{stream, Future, Stream};
 use rand::{thread_rng, Rng, ThreadRng};
-use tokio_postgres::{connect, Client, Statement, TlsMode};
+use tokio_postgres::{connect, Client, NoTls, Statement};
 
 use crate::models::{Fortune, World};
 
@@ -17,10 +17,10 @@ pub struct PgConnection {
 
 impl PgConnection {
     pub fn connect(db_url: &str) -> impl Future<Item = PgConnection, Error = ()> {
-        let hs = connect(db_url.parse().unwrap(), TlsMode::None);
+        let hs = connect(db_url, NoTls);
 
         hs.map_err(|_| panic!("can not connect to postgresql"))
-            .and_then(|(cl, conn)| {
+            .and_then(|(mut cl, conn)| {
                 actix_rt::spawn(conn.map_err(|e| panic!("{}", e)));
 
                 join_all(vec![
@@ -49,7 +49,7 @@ impl PgConnection {
         self.cl
             .query(&self.world, &[&random_id])
             .into_future()
-            .map_err(|e| io::Error::new(io::ErrorKind::Other, e.0))
+            .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("{:?}", e.0)))
             .and_then(|(row, _)| {
                 let row = row.unwrap();
                 Ok(World {
@@ -70,7 +70,9 @@ impl PgConnection {
                 self.cl
                     .query(&self.world, &[&w_id])
                     .into_future()
-                    .map_err(|e| io::Error::new(io::ErrorKind::Other, e.0))
+                    .map_err(|e| {
+                        io::Error::new(io::ErrorKind::Other, format!("{:?}", e.0))
+                    })
                     .and_then(|(row, _)| {
                         let row = row.unwrap();
                         Ok(World {
@@ -96,7 +98,9 @@ impl PgConnection {
                 self.cl
                     .query(&self.world, &[&w_id])
                     .into_future()
-                    .map_err(|e| io::Error::new(io::ErrorKind::Other, e.0))
+                    .map_err(|e| {
+                        io::Error::new(io::ErrorKind::Other, format!("{:?}", e.0))
+                    })
                     .and_then(move |(row, _)| {
                         let row = row.unwrap();
                         Ok(World {
@@ -107,7 +111,7 @@ impl PgConnection {
             );
         }
 
-        let cl = self.cl.clone();
+        let mut cl = self.cl.clone();
         stream::futures_unordered(worlds)
             .collect()
             .and_then(move |worlds| {
@@ -124,13 +128,18 @@ impl PgConnection {
                     " ORDER BY 1) AS temp(id, randomnumber) WHERE temp.id = world.id",
                 );
 
-                cl.batch_execute(&update)
-                    .map_err(|e| io::Error::new(io::ErrorKind::Other, e))
+                cl.simple_query(&update)
+                    .collect()
+                    .map_err(|e| {
+                        io::Error::new(io::ErrorKind::Other, format!("{:?}", e))
+                    })
                     .and_then(|_| Ok(worlds))
             })
     }
 
-    pub fn tell_fortune(&self) -> impl Future<Item = Vec<Fortune>, Error = io::Error> {
+    pub fn tell_fortune(
+        &mut self,
+    ) -> impl Future<Item = Vec<Fortune>, Error = io::Error> {
         let mut items = Vec::new();
         items.push(Fortune {
             id: 0,
@@ -139,6 +148,7 @@ impl PgConnection {
 
         self.cl
             .query(&self.fortune, &[])
+            .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("{:?}", e)))
             .fold(items, move |mut items, row| {
                 items.push(Fortune {
                     id: row.get(0),
@@ -146,7 +156,7 @@ impl PgConnection {
                 });
                 Ok::<_, io::Error>(items)
             })
-            .map_err(|e| io::Error::new(io::ErrorKind::Other, e))
+            .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("{:?}", e)))
             .and_then(|mut items| {
                 items.sort_by(|it, next| it.message.cmp(&next.message));
                 Ok(items)

+ 11 - 7
frameworks/Rust/actix/src/main_platform.rs

@@ -14,7 +14,7 @@ use actix_http::http::{HeaderValue, StatusCode};
 use actix_http::{Error, HttpService, KeepAlive, Request, Response};
 use actix_server::{Server, ServerConfig};
 use actix_service::{NewService, Service};
-use bytes::{Bytes, BytesMut};
+use bytes::{BufMut, Bytes, BytesMut};
 use futures::future::{join_all, ok, Either, FutureResult};
 use futures::{Async, Future, Poll};
 
@@ -23,7 +23,7 @@ mod models;
 mod utils;
 
 use crate::db_pg_direct::PgConnection;
-use crate::utils::{escape, Message, Writer, SIZE};
+use crate::utils::{Message, Writer, SIZE};
 
 const FORTUNES_START: &[u8] = b"<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>";
 const FORTUNES_ROW_START: &[u8] = b"<tr><td>";
@@ -133,13 +133,17 @@ impl Service for App {
                 Either::B(Box::new(fut.from_err().and_then(move |fortunes| {
                     let mut body = BytesMut::with_capacity(2048);
                     let mut writer = Writer(&mut body);
-                    let _ = writer.write(FORTUNES_START);
+                    let _ = writer.0.put_slice(FORTUNES_START);
                     fortunes.into_iter().fold((), |_, row| {
-                        let _ = writer.write(FORTUNES_ROW_START);
+                        let _ = writer.0.put_slice(FORTUNES_ROW_START);
                         let _ = write!(&mut writer, "{}", row.id);
-                        let _ = writer.write(FORTUNES_COLUMN);
-                        escape(&mut writer, row.message);
-                        let _ = writer.write(FORTUNES_ROW_END);
+                        let _ = writer.0.put_slice(FORTUNES_COLUMN);
+                        let _ = write!(
+                            &mut writer,
+                            "{}",
+                            v_htmlescape::escape(&row.message)
+                        );
+                        let _ = writer.0.put_slice(FORTUNES_ROW_END);
                         ()
                     });
                     let _ = writer.write(FORTUNES_END);

+ 11 - 11
frameworks/Rust/actix/src/utils.rs

@@ -1,7 +1,7 @@
 #![allow(dead_code)]
 use std::{cmp, io};
 
-use bytes::BytesMut;
+use bytes::{BufMut, BytesMut};
 
 pub const SIZE: usize = 31;
 
@@ -14,7 +14,7 @@ pub struct Writer<'a>(pub &'a mut BytesMut);
 
 impl<'a> io::Write for Writer<'a> {
     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
-        self.0.extend_from_slice(buf);
+        self.0.put_slice(buf);
         Ok(buf.len())
     }
     fn flush(&mut self) -> io::Result<()> {
@@ -38,38 +38,38 @@ fn escapable(b: u8) -> bool {
     }
 }
 
-pub fn escape<T: io::Write>(writer: &mut T, s: String) {
+pub fn escape(writer: &mut Writer, s: String) {
     let bytes = s.as_bytes();
     let mut last_pos = 0;
     for (idx, b) in s.as_bytes().iter().enumerate() {
         if escapable(*b) {
-            let _ = writer.write(&bytes[last_pos..idx]);
+            let _ = writer.0.put_slice(&bytes[last_pos..idx]);
 
             last_pos = idx + 1;
             match *b {
                 b'<' => {
-                    let _ = writer.write(b"&lt;");
+                    let _ = writer.0.put_slice(b"&lt;");
                 }
                 b'>' => {
-                    let _ = writer.write(b"&gt;");
+                    let _ = writer.0.put_slice(b"&gt;");
                 }
                 b'&' => {
-                    let _ = writer.write(b"&amp;");
+                    let _ = writer.0.put_slice(b"&amp;");
                 }
                 b'"' => {
-                    let _ = writer.write(b"&quot;");
+                    let _ = writer.0.put_slice(b"&quot;");
                 }
                 b'\'' => {
-                    let _ = writer.write(b"&#x27;");
+                    let _ = writer.0.put_slice(b"&#x27;");
                 }
                 b'/' => {
-                    let _ = writer.write(b"&#x2f;");
+                    let _ = writer.0.put_slice(b"&#x2f;");
                 }
                 _ => panic!("incorrect indexing"),
             }
         }
     }
     if last_pos < bytes.len() - 1 {
-        let _ = writer.write(&bytes[last_pos..]);
+        let _ = writer.0.put_slice(&bytes[last_pos..]);
     }
 }