Browse Source

chore(viz): use rand in pg case (#8165)

Fangdun Tsai 2 years ago
parent
commit
da31f49539

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

@@ -29,6 +29,7 @@ hyper = "0.14.25"
 atoi = "2.0"
 atoi = "2.0"
 serde = { version = "1.0", features = ["derive"] }
 serde = { version = "1.0", features = ["derive"] }
 nanorand = "0.7"
 nanorand = "0.7"
+rand = { version = "0.8.5", features = ["small_rng"] }
 thiserror = "1.0"
 thiserror = "1.0"
 futures-util = "0.3.27"
 futures-util = "0.3.27"
 
 
@@ -54,5 +55,4 @@ sailfish = { version = "0.6.0", optional = true }
 
 
 [profile.release]
 [profile.release]
 lto = true
 lto = true
-opt-level = 3
 codegen-units = 1
 codegen-units = 1

+ 14 - 14
frameworks/Rust/viz/src/db_pg.rs

@@ -1,7 +1,7 @@
 use std::{borrow::Cow, collections::HashMap, fmt::Write, io, sync::Arc};
 use std::{borrow::Cow, collections::HashMap, fmt::Write, io, sync::Arc};
 
 
 use futures_util::{stream::FuturesUnordered, TryFutureExt, TryStreamExt};
 use futures_util::{stream::FuturesUnordered, TryFutureExt, TryStreamExt};
-use nanorand::{Rng, WyRand};
+use rand::{rngs::SmallRng, thread_rng, Rng, SeedableRng};
 use tokio_postgres::{connect, types::ToSql, Client, NoTls, Statement};
 use tokio_postgres::{connect, types::ToSql, Client, NoTls, Statement};
 use viz::{Error, IntoResponse, Response, StatusCode};
 use viz::{Error, IntoResponse, Response, StatusCode};
 
 
@@ -33,7 +33,6 @@ impl IntoResponse for PgError {
 
 
 /// Postgres interface
 /// Postgres interface
 pub struct PgConnection {
 pub struct PgConnection {
-    rng: WyRand,
     client: Client,
     client: Client,
     world: Statement,
     world: Statement,
     fortune: Statement,
     fortune: Statement,
@@ -41,7 +40,7 @@ pub struct PgConnection {
 }
 }
 
 
 impl PgConnection {
 impl PgConnection {
-    pub async fn connect(db_url: &str) -> Self {
+    pub async fn connect(db_url: &str) -> Arc<Self> {
         let (client, conn) = connect(db_url, NoTls)
         let (client, conn) = connect(db_url, NoTls)
             .await
             .await
             .expect("can not connect to postgresql");
             .expect("can not connect to postgresql");
@@ -63,14 +62,14 @@ impl PgConnection {
             q.push_str("UPDATE world SET randomnumber = CASE id ");
             q.push_str("UPDATE world SET randomnumber = CASE id ");
 
 
             for _ in 1..=num {
             for _ in 1..=num {
-                let _ = write!(q, "when ${} then ${} ", pl, pl + 1);
+                let _ = write!(q, "when ${pl} then ${} ", pl + 1);
                 pl += 2;
                 pl += 2;
             }
             }
 
 
             q.push_str("ELSE randomnumber END WHERE id IN (");
             q.push_str("ELSE randomnumber END WHERE id IN (");
 
 
             for _ in 1..=num {
             for _ in 1..=num {
-                let _ = write!(q, "${},", pl);
+                let _ = write!(q, "${pl},");
                 pl += 1;
                 pl += 1;
             }
             }
 
 
@@ -85,13 +84,12 @@ impl PgConnection {
             .await
             .await
             .unwrap();
             .unwrap();
 
 
-        PgConnection {
-            rng: WyRand::new(),
+        Arc::new(PgConnection {
             world,
             world,
             client,
             client,
             fortune,
             fortune,
             updates,
             updates,
-        }
+        })
     }
     }
 }
 }
 
 
@@ -105,17 +103,19 @@ impl PgConnection {
     }
     }
 
 
     pub async fn get_world(&self) -> Result<World, PgError> {
     pub async fn get_world(&self) -> Result<World, PgError> {
-        let random_id = self.rng.clone().generate_range(RANGE);
+        let mut rng = SmallRng::from_rng(&mut thread_rng()).unwrap();
+        let random_id = rng.gen_range(RANGE);
+
         self.query_one_world(random_id).await
         self.query_one_world(random_id).await
     }
     }
 
 
     pub async fn get_worlds(&self, num: u16) -> Result<Vec<World>, PgError> {
     pub async fn get_worlds(&self, num: u16) -> Result<Vec<World>, PgError> {
-        let mut rng = self.rng.clone();
+        let mut rng = SmallRng::from_rng(&mut thread_rng()).unwrap();
 
 
         let worlds = FuturesUnordered::new();
         let worlds = FuturesUnordered::new();
 
 
         for _ in 0..num {
         for _ in 0..num {
-            let id = rng.generate_range(RANGE);
+            let id = rng.gen_range(RANGE);
             worlds.push(self.query_one_world(id));
             worlds.push(self.query_one_world(id));
         }
         }
 
 
@@ -123,13 +123,13 @@ impl PgConnection {
     }
     }
 
 
     pub async fn update(&self, num: u16) -> Result<Vec<World>, PgError> {
     pub async fn update(&self, num: u16) -> Result<Vec<World>, PgError> {
-        let mut rng = self.rng.clone();
+        let mut rng = SmallRng::from_rng(&mut thread_rng()).unwrap();
 
 
         let worlds = FuturesUnordered::new();
         let worlds = FuturesUnordered::new();
 
 
         for _ in 0..num {
         for _ in 0..num {
-            let id = rng.generate_range(RANGE);
-            let rid = rng.generate_range(RANGE);
+            let id = rng.gen_range(RANGE);
+            let rid = rng.gen_range(RANGE);
 
 
             worlds.push(self.query_one_world(id).map_ok(move |mut world| {
             worlds.push(self.query_one_world(id).map_ok(move |mut world| {
                 world.randomnumber = rid;
                 world.randomnumber = rid;

+ 1 - 1
frameworks/Rust/viz/src/main_pg.rs

@@ -96,7 +96,7 @@ async fn serve() {
         .get("/fortunes", fortunes)
         .get("/fortunes", fortunes)
         .get("/queries", queries)
         .get("/queries", queries)
         .get("/updates", updates)
         .get("/updates", updates)
-        .with(State::new(Arc::new(conn)));
+        .with(State::new(conn));
 
 
     server::builder()
     server::builder()
         .serve(ServiceMaker::from(app))
         .serve(ServiceMaker::from(app))