http_bench.rs 7.7 KB
Newer Older
R
Ryan Dahl 已提交
1 2 3 4
/// To run this benchmark:
///
/// > DENO_BUILD_MODE=release ./tools/build.py && \
///   ./target/release/deno_core_http_bench --multi-thread
5
extern crate deno;
R
Ryan Dahl 已提交
6 7 8 9 10 11 12 13 14
extern crate futures;
extern crate libc;
extern crate tokio;

#[macro_use]
extern crate log;
#[macro_use]
extern crate lazy_static;

15
use deno::*;
R
Ryan Dahl 已提交
16 17 18 19 20 21 22 23 24
use futures::future::lazy;
use std::collections::HashMap;
use std::env;
use std::net::SocketAddr;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::sync::Mutex;
use tokio::prelude::*;

25 26 27 28 29 30 31 32 33 34 35 36 37 38
static LOGGER: Logger = Logger;
struct Logger;
impl log::Log for Logger {
  fn enabled(&self, metadata: &log::Metadata) -> bool {
    metadata.level() <= log::max_level()
  }
  fn log(&self, record: &log::Record) {
    if self.enabled(record.metadata()) {
      println!("{} - {}", record.level(), record.args());
    }
  }
  fn flush(&self) {}
}

R
Ryan Dahl 已提交
39 40 41 42 43 44
const OP_LISTEN: i32 = 1;
const OP_ACCEPT: i32 = 2;
const OP_READ: i32 = 3;
const OP_WRITE: i32 = 4;
const OP_CLOSE: i32 = 5;

R
Ryan Dahl 已提交
45
#[derive(Clone, Debug, PartialEq)]
46 47 48 49 50 51 52
pub struct Record {
  pub promise_id: i32,
  pub op_id: i32,
  pub arg: i32,
  pub result: i32,
}

R
Ryan Dahl 已提交
53 54 55 56 57 58 59 60
impl Into<Buf> for Record {
  fn into(self) -> Buf {
    let buf32 = vec![self.promise_id, self.op_id, self.arg, self.result]
      .into_boxed_slice();
    let ptr = Box::into_raw(buf32) as *mut [u8; 16];
    unsafe { Box::from_raw(ptr) }
  }
}
61

R
Ryan Dahl 已提交
62 63
impl From<&[u8]> for Record {
  fn from(s: &[u8]) -> Record {
B
Bert Belder 已提交
64
    #[allow(clippy::cast_ptr_alignment)]
R
Ryan Dahl 已提交
65 66 67 68 69 70 71 72 73
    let ptr = s.as_ptr() as *const i32;
    let ints = unsafe { std::slice::from_raw_parts(ptr, 4) };
    Record {
      promise_id: ints[0],
      op_id: ints[1],
      arg: ints[2],
      result: ints[3],
    }
  }
74 75
}

R
Ryan Dahl 已提交
76 77 78
impl From<Buf> for Record {
  fn from(buf: Buf) -> Record {
    assert_eq!(buf.len(), 4 * 4);
B
Bert Belder 已提交
79
    #[allow(clippy::cast_ptr_alignment)]
R
Ryan Dahl 已提交
80 81 82 83 84 85 86 87 88
    let ptr = Box::into_raw(buf) as *mut [i32; 4];
    let ints: Box<[i32]> = unsafe { Box::from_raw(ptr) };
    assert_eq!(ints.len(), 4);
    Record {
      promise_id: ints[0],
      op_id: ints[1],
      arg: ints[2],
      result: ints[3],
    }
89 90 91
  }
}

R
Ryan Dahl 已提交
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
#[test]
fn test_record_from() {
  let r = Record {
    promise_id: 1,
    op_id: 2,
    arg: 3,
    result: 4,
  };
  let expected = r.clone();
  let buf: Buf = r.into();
  #[cfg(target_endian = "little")]
  assert_eq!(
    buf,
    vec![1u8, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0].into_boxed_slice()
  );
  let actual = Record::from(buf);
  assert_eq!(actual, expected);
  // TODO test From<&[u8]> for Record
110 111
}

R
Ryan Dahl 已提交
112 113 114 115
pub type HttpBenchOp = dyn Future<Item = i32, Error = std::io::Error> + Send;

struct HttpBench();

116
impl Dispatch for HttpBench {
R
Ryan Dahl 已提交
117
  fn dispatch(
118
    &mut self,
R
Ryan Dahl 已提交
119
    control: &[u8],
120
    zero_copy_buf: deno_buf,
R
Ryan Dahl 已提交
121 122
  ) -> (bool, Box<Op>) {
    let record = Record::from(control);
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
    let is_sync = record.promise_id == 0;
    let http_bench_op = match record.op_id {
      OP_LISTEN => {
        assert!(is_sync);
        op_listen()
      }
      OP_CLOSE => {
        assert!(is_sync);
        let rid = record.arg;
        op_close(rid)
      }
      OP_ACCEPT => {
        assert!(!is_sync);
        let listener_rid = record.arg;
        op_accept(listener_rid)
      }
      OP_READ => {
        assert!(!is_sync);
        let rid = record.arg;
        op_read(rid, zero_copy_buf)
      }
      OP_WRITE => {
        assert!(!is_sync);
        let rid = record.arg;
        op_write(rid, zero_copy_buf)
      }
      _ => panic!("bad op {}", record.op_id),
    };
    let mut record_a = record.clone();
    let mut record_b = record.clone();

    let op = Box::new(
      http_bench_op
        .and_then(move |result| {
          record_a.result = result;
          Ok(record_a)
        }).or_else(|err| -> Result<Record, ()> {
          eprintln!("unexpected err {}", err);
          record_b.result = -1;
          Ok(record_b)
R
Ryan Dahl 已提交
163 164 165
        }).then(|result| -> Result<Buf, ()> {
          let record = result.unwrap();
          Ok(record.into())
166 167 168 169 170 171
        }),
    );
    (is_sync, op)
  }
}

R
Ryan Dahl 已提交
172 173 174 175 176
fn main() {
  let main_future = lazy(move || {
    // TODO currently isolate.execute() must be run inside tokio, hence the
    // lazy(). It would be nice to not have that contraint. Probably requires
    // using v8::MicrotasksPolicy::kExplicit
R
Ryan Dahl 已提交
177 178 179 180 181 182 183 184 185

    let js_source = include_str!("http_bench.js");

    let startup_data = StartupData::Script(Script {
      source: js_source,
      filename: "http_bench.js",
    });

    let isolate = deno::Isolate::new(startup_data, HttpBench());
186

R
Ryan Dahl 已提交
187 188 189 190 191 192 193
    isolate.then(|r| {
      js_check(r);
      Ok(())
    })
  });

  let args: Vec<String> = env::args().collect();
194
  let args = deno::v8_set_flags(args);
195 196 197 198 199 200 201 202 203

  log::set_logger(&LOGGER).unwrap();
  log::set_max_level(if args.iter().any(|a| a == "-D") {
    log::LevelFilter::Debug
  } else {
    log::LevelFilter::Warn
  });

  if args.iter().any(|a| a == "--multi-thread") {
R
Ryan Dahl 已提交
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
    println!("multi-thread");
    tokio::run(main_future);
  } else {
    println!("single-thread");
    tokio::runtime::current_thread::run(main_future);
  }
}

enum Repr {
  TcpListener(tokio::net::TcpListener),
  TcpStream(tokio::net::TcpStream),
}

type ResourceTable = HashMap<i32, Repr>;
lazy_static! {
  static ref RESOURCE_TABLE: Mutex<ResourceTable> = Mutex::new(HashMap::new());
  static ref NEXT_RID: AtomicUsize = AtomicUsize::new(3);
}

fn new_rid() -> i32 {
  let rid = NEXT_RID.fetch_add(1, Ordering::SeqCst);
  rid as i32
}

228
fn op_accept(listener_rid: i32) -> Box<HttpBenchOp> {
R
Ryan Dahl 已提交
229 230 231 232 233 234 235
  debug!("accept {}", listener_rid);
  Box::new(
    futures::future::poll_fn(move || {
      let mut table = RESOURCE_TABLE.lock().unwrap();
      let maybe_repr = table.get_mut(&listener_rid);
      match maybe_repr {
        Some(Repr::TcpListener(ref mut listener)) => listener.poll_accept(),
236
        _ => panic!("bad rid {}", listener_rid),
R
Ryan Dahl 已提交
237 238 239 240 241 242 243 244
      }
    }).and_then(move |(stream, addr)| {
      debug!("accept success {}", addr);
      let rid = new_rid();

      let mut guard = RESOURCE_TABLE.lock().unwrap();
      guard.insert(rid, Repr::TcpStream(stream));

245
      Ok(rid as i32)
R
Ryan Dahl 已提交
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
fn op_listen() -> Box<HttpBenchOp> {
  debug!("listen");

  Box::new(lazy(move || {
    let addr = "127.0.0.1:4544".parse::<SocketAddr>().unwrap();
    let listener = tokio::net::TcpListener::bind(&addr).unwrap();
    let rid = new_rid();

    let mut guard = RESOURCE_TABLE.lock().unwrap();
    guard.insert(rid, Repr::TcpListener(listener));
    futures::future::ok(rid)
  }))
}

fn op_close(rid: i32) -> Box<HttpBenchOp> {
  debug!("close");
  Box::new(lazy(move || {
    let mut table = RESOURCE_TABLE.lock().unwrap();
    let r = table.remove(&rid);
    let result = if r.is_some() { 0 } else { -1 };
    futures::future::ok(result)
  }))
}

fn op_read(rid: i32, mut zero_copy_buf: deno_buf) -> Box<HttpBenchOp> {
R
Ryan Dahl 已提交
275 276 277 278 279 280 281 282 283 284 285 286 287
  debug!("read rid={}", rid);
  Box::new(
    futures::future::poll_fn(move || {
      let mut table = RESOURCE_TABLE.lock().unwrap();
      let maybe_repr = table.get_mut(&rid);
      match maybe_repr {
        Some(Repr::TcpStream(ref mut stream)) => {
          stream.poll_read(&mut zero_copy_buf)
        }
        _ => panic!("bad rid"),
      }
    }).and_then(move |nread| {
      debug!("read success {}", nread);
288
      Ok(nread as i32)
R
Ryan Dahl 已提交
289 290 291 292
    }),
  )
}

293
fn op_write(rid: i32, zero_copy_buf: deno_buf) -> Box<HttpBenchOp> {
R
Ryan Dahl 已提交
294 295 296 297 298 299 300 301 302 303 304 305 306
  debug!("write rid={}", rid);
  Box::new(
    futures::future::poll_fn(move || {
      let mut table = RESOURCE_TABLE.lock().unwrap();
      let maybe_repr = table.get_mut(&rid);
      match maybe_repr {
        Some(Repr::TcpStream(ref mut stream)) => {
          stream.poll_write(&zero_copy_buf)
        }
        _ => panic!("bad rid"),
      }
    }).and_then(move |nwritten| {
      debug!("write success {}", nwritten);
307
      Ok(nwritten as i32)
R
Ryan Dahl 已提交
308 309 310 311 312 313 314 315 316
    }),
  )
}

fn js_check(r: Result<(), JSError>) {
  if let Err(e) = r {
    panic!(e.to_string());
  }
}