dispatch_minimal.rs 4.5 KB
Newer Older
R
Ryan Dahl 已提交
1 2 3 4 5 6
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
// Do not add flatbuffer dependencies to this module.
//! Connects to js/dispatch_minimal.ts sendAsyncMinimal This acts as a faster
//! alternative to flatbuffers using a very simple list of int32s to lay out
//! messages. The first i32 is used to determine if a message a flatbuffer
//! message or a "minimal" message.
7
use crate::deno_error::GetErrorKind;
8
use crate::msg::ErrorKind;
9
use byteorder::{LittleEndian, WriteBytesExt};
R
Ryan Dahl 已提交
10
use deno::Buf;
A
andy finch 已提交
11
use deno::CoreOp;
R
Ryan Dahl 已提交
12
use deno::ErrBox;
R
Ryan Dahl 已提交
13 14 15 16
use deno::Op;
use deno::PinnedBuf;
use futures::Future;

R
Ryan Dahl 已提交
17
pub type MinimalOp = dyn Future<Item = i32, Error = ErrBox> + Send;
18

R
Ryan Dahl 已提交
19 20 21
#[derive(Copy, Clone, Debug, PartialEq)]
// This corresponds to RecordMinimal on the TS side.
pub struct Record {
22
  pub promise_id: i32,
R
Ryan Dahl 已提交
23 24 25 26 27 28
  pub arg: i32,
  pub result: i32,
}

impl Into<Buf> for Record {
  fn into(self) -> Buf {
R
Ryan Dahl 已提交
29
    let vec = vec![self.promise_id, self.arg, self.result];
R
Ryan Dahl 已提交
30
    let buf32 = vec.into_boxed_slice();
R
Ryan Dahl 已提交
31
    let ptr = Box::into_raw(buf32) as *mut [u8; 3 * 4];
R
Ryan Dahl 已提交
32 33 34 35
    unsafe { Box::from_raw(ptr) }
  }
}

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
pub struct ErrorRecord {
  pub promise_id: i32,
  pub arg: i32,
  pub error_code: i32,
  pub error_message: Vec<u8>,
}

impl Into<Buf> for ErrorRecord {
  fn into(self) -> Buf {
    let v32: Vec<i32> = vec![self.promise_id, self.arg, self.error_code];
    let mut v8: Vec<u8> = Vec::new();
    for n in v32 {
      v8.write_i32::<LittleEndian>(n).unwrap();
    }
    let mut message = self.error_message;
    // Align to 32bit word, padding with the space character.
    message.resize((message.len() + 3usize) & !3usize, b' ');
    v8.append(&mut message);
    v8.into_boxed_slice()
  }
}

#[test]
fn test_error_record() {
  let expected = vec![
    1, 0, 0, 0, 255, 255, 255, 255, 10, 0, 0, 0, 69, 114, 114, 111, 114, 32,
    32, 32,
  ];
  let err_record = ErrorRecord {
    promise_id: 1,
    arg: -1,
    error_code: 10,
    error_message: "Error".to_string().as_bytes().to_owned(),
  };
  let buf: Buf = err_record.into();
  assert_eq!(buf, expected.into_boxed_slice());
}

R
Ryan Dahl 已提交
74 75 76 77 78 79 80
pub fn parse_min_record(bytes: &[u8]) -> Option<Record> {
  if bytes.len() % std::mem::size_of::<i32>() != 0 {
    return None;
  }
  let p = bytes.as_ptr();
  #[allow(clippy::cast_ptr_alignment)]
  let p32 = p as *const i32;
81
  let s = unsafe { std::slice::from_raw_parts(p32, bytes.len() / 4) };
R
Ryan Dahl 已提交
82

R
Ryan Dahl 已提交
83
  if s.len() != 3 {
R
Ryan Dahl 已提交
84 85 86
    return None;
  }
  let ptr = s.as_ptr();
R
Ryan Dahl 已提交
87
  let ints = unsafe { std::slice::from_raw_parts(ptr, 3) };
R
Ryan Dahl 已提交
88
  Some(Record {
R
Ryan Dahl 已提交
89 90 91
    promise_id: ints[0],
    arg: ints[1],
    result: ints[2],
R
Ryan Dahl 已提交
92 93 94 95 96
  })
}

#[test]
fn test_parse_min_record() {
R
Ryan Dahl 已提交
97
  let buf = vec![1, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0];
R
Ryan Dahl 已提交
98 99 100
  assert_eq!(
    parse_min_record(&buf),
    Some(Record {
101 102 103
      promise_id: 1,
      arg: 3,
      result: 4,
R
Ryan Dahl 已提交
104 105 106 107 108 109 110 111 112 113
    })
  );

  let buf = vec![];
  assert_eq!(parse_min_record(&buf), None);

  let buf = vec![5];
  assert_eq!(parse_min_record(&buf), None);
}

114 115 116 117
pub fn minimal_op<D>(d: D) -> impl Fn(&[u8], Option<PinnedBuf>) -> CoreOp
where
  D: Fn(i32, Option<PinnedBuf>) -> Box<MinimalOp>,
{
118
  move |control: &[u8], zero_copy: Option<PinnedBuf>| {
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
    let mut record = match parse_min_record(control) {
      Some(r) => r,
      None => {
        let error_record = ErrorRecord {
          promise_id: 0,
          arg: -1,
          error_code: ErrorKind::InvalidInput as i32,
          error_message: "Unparsable control buffer"
            .to_string()
            .as_bytes()
            .to_owned(),
        };
        return Op::Sync(error_record.into());
      }
    };
134 135 136
    let is_sync = record.promise_id == 0;
    let rid = record.arg;
    let min_op = d(rid, zero_copy);
R
Ryan Dahl 已提交
137

138 139 140 141 142
    // Convert to CoreOp
    let fut = Box::new(min_op.then(move |result| -> Result<Buf, ()> {
      match result {
        Ok(r) => {
          record.result = r;
143
          Ok(record.into())
144 145
        }
        Err(err) => {
146 147 148 149 150 151 152
          let error_record = ErrorRecord {
            promise_id: record.promise_id,
            arg: -1,
            error_code: err.kind() as i32,
            error_message: err.to_string().as_bytes().to_owned(),
          };
          Ok(error_record.into())
153
        }
R
Ryan Dahl 已提交
154
      }
155
    }));
156

157 158 159 160 161 162 163 164 165 166
    if is_sync {
      // Warning! Possible deadlocks can occur if we try to wait for a future
      // while in a future. The safe but expensive alternative is to use
      // tokio_util::block_on.
      // This block is only exercised for readSync and writeSync, which I think
      // works since they're simple polling futures.
      Op::Sync(fut.wait().unwrap())
    } else {
      Op::Async(fut)
    }
167
  }
R
Ryan Dahl 已提交
168
}