首頁  >  文章  >  web前端  >  deno通訊實作的方法(附程式碼)

deno通訊實作的方法(附程式碼)

不言
不言轉載
2019-03-11 17:02:272487瀏覽

這篇文章帶給大家的內容是關於deno通訊實現的方法(附程式碼),有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。

通訊方式

deno執行程式碼和node相似,包含同步和非同步的方式, 非同步方式透過Promise.then實現。

Typescript/Javascript呼叫rust

在上一節講到deno的啟動時會初始化v8 isolate實例,在初始化的過程中,會將c 的函數綁定到v8 isolate的實例上,在v8執行Javascript程式碼時,可以像呼叫Javascript函數一樣呼叫這些綁定的函數。具體的綁定實作如下:

void InitializeContext(v8::Isolate* isolate, v8::Local<v8::Context> context) {
  v8::HandleScope handle_scope(isolate);
  v8::Context::Scope context_scope(context);

  auto global = context->Global();

  auto deno_val = v8::Object::New(isolate);
  CHECK(global->Set(context, deno::v8_str("libdeno"), deno_val).FromJust());

  auto print_tmpl = v8::FunctionTemplate::New(isolate, Print);
  auto print_val = print_tmpl->GetFunction(context).ToLocalChecked();
  CHECK(deno_val->Set(context, deno::v8_str("print"), print_val).FromJust());

  auto recv_tmpl = v8::FunctionTemplate::New(isolate, Recv);
  auto recv_val = recv_tmpl->GetFunction(context).ToLocalChecked();
  CHECK(deno_val->Set(context, deno::v8_str("recv"), recv_val).FromJust());

  auto send_tmpl = v8::FunctionTemplate::New(isolate, Send);
  auto send_val = send_tmpl->GetFunction(context).ToLocalChecked();
  CHECK(deno_val->Set(context, deno::v8_str("send"), send_val).FromJust());

  auto eval_context_tmpl = v8::FunctionTemplate::New(isolate, EvalContext);
  auto eval_context_val =
      eval_context_tmpl->GetFunction(context).ToLocalChecked();
  CHECK(deno_val->Set(context, deno::v8_str("evalContext"), eval_context_val)
            .FromJust());

  auto error_to_json_tmpl = v8::FunctionTemplate::New(isolate, ErrorToJSON);
  auto error_to_json_val =
      error_to_json_tmpl->GetFunction(context).ToLocalChecked();
  CHECK(deno_val->Set(context, deno::v8_str("errorToJSON"), error_to_json_val)
            .FromJust());

  CHECK(deno_val->SetAccessor(context, deno::v8_str("shared"), Shared)
            .FromJust());
}

在完成綁定之後,​​在Typescript中可以透過以下程式碼實作c 方法和Typescript方法的對應

libdeno.ts
interface Libdeno {
  recv(cb: MessageCallback): void;

  send(control: ArrayBufferView, data?: ArrayBufferView): null | Uint8Array;

  print(x: string, isErr?: boolean): void;

  shared: ArrayBuffer;

  /** Evaluate provided code in the current context.
   * It differs from eval(...) in that it does not create a new context.
   * Returns an array: [output, errInfo].
   * If an error occurs, `output` becomes null and `errInfo` is non-null.
   */
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  evalContext(code: string): [any, EvalErrorInfo | null];

  errorToJSON: (e: Error) => string;
}

export const libdeno = window.libdeno as Libdeno;

執行Typescript程式碼時,只需要引入libdeno,就直接呼叫c 方法,例如:

import { libdeno } from "./libdeno";
function sendInternal(
  builder: flatbuffers.Builder,
  innerType: msg.Any,
  inner: flatbuffers.Offset,
  data: undefined | ArrayBufferView,
  sync = true
): [number, null | Uint8Array] {
  const cmdId = nextCmdId++;
  msg.Base.startBase(builder);
  msg.Base.addInner(builder, inner);
  msg.Base.addInnerType(builder, innerType);
  msg.Base.addSync(builder, sync);
  msg.Base.addCmdId(builder, cmdId);
  builder.finish(msg.Base.endBase(builder));
  const res = libdeno.send(builder.asUint8Array(), data);
  builder.inUse = false;
  return [cmdId, res];
}

呼叫libdeno.send方法可以將資料傳給c ,然後透過c 去呼叫rust程式碼實現具體的工程操作。

Typescript層同步非同步實作

同步

在Typescript中只需要設定sendInternal方法的sync參數為true即可,在rust中會根據sync參數去判斷是執行同步或非同步操作,如果sync為true,libdeono.send方法會傳回執行的結果,rust和typescript之間傳遞資料需要將資料序列化,這裡序列化操作使用的是flatbuffer函式庫。

const [cmdId, resBuf] = sendInternal(builder, innerType, inner, data, true);
非同步實現

同理,實現異步方式,只需要設定sync參數為false即可,但是非同步操作和同步相比,多了回掉方法,在執行非同步通信時,libdeno.send方法會傳回一個唯一的cmdId標誌這次呼叫操作。同時在非同步通訊完成後,會建立一個promise對象,將cmdId作為key,promise作為value,加入map中。程式碼如下:

const [cmdId, resBuf] = sendInternal(builder, innerType, inner, data, false);
  util.assert(resBuf == null);
  const promise = util.createResolvable<msg.Base>();
  promiseTable.set(cmdId, promise);
  return promise;

rust實作同步和非同步

當在Typescript中呼叫libdeno.send方法時,呼叫了C 檔案binding.cc中的Send方法,該方法是在deno初始化時綁定到v8 isolate上去的。在Send方法中去呼叫了ops.rs檔案中的dispatch方法,該方法實作了訊息到函數的映射。每個類型的消息對應了一種函數,例如讀取文件訊息對應了讀取文件的函數。

pub fn dispatch(
  isolate: &Isolate,
  control: libdeno::deno_buf,
  data: libdeno::deno_buf,
) -> (bool, Box<Op>) {
  let base = msg::get_root_as_base(&control);
  let is_sync = base.sync();
  let inner_type = base.inner_type();
  let cmd_id = base.cmd_id();

  let op: Box<Op> = if inner_type == msg::Any::SetTimeout {
    // SetTimeout is an exceptional op: the global timeout field is part of the
    // Isolate state (not the IsolateState state) and it must be updated on the
    // main thread.
    assert_eq!(is_sync, true);
    op_set_timeout(isolate, &base, data)
  } else {
    // Handle regular ops.
    let op_creator: OpCreator = match inner_type {
      msg::Any::Accept => op_accept,
      msg::Any::Chdir => op_chdir,
      msg::Any::Chmod => op_chmod,
      msg::Any::Close => op_close,
      msg::Any::FetchModuleMetaData => op_fetch_module_meta_data,
      msg::Any::CopyFile => op_copy_file,
      msg::Any::Cwd => op_cwd,
      msg::Any::Dial => op_dial,
      msg::Any::Environ => op_env,
      msg::Any::Exit => op_exit,
      msg::Any::Fetch => op_fetch,
      msg::Any::FormatError => op_format_error,
      msg::Any::Listen => op_listen,
      msg::Any::MakeTempDir => op_make_temp_dir,
      msg::Any::Metrics => op_metrics,
      msg::Any::Mkdir => op_mkdir,
      msg::Any::Open => op_open,
      msg::Any::ReadDir => op_read_dir,
      msg::Any::ReadFile => op_read_file,
      msg::Any::Readlink => op_read_link,
      msg::Any::Read => op_read,
      msg::Any::Remove => op_remove,
      msg::Any::Rename => op_rename,
      msg::Any::ReplReadline => op_repl_readline,
      msg::Any::ReplStart => op_repl_start,
      msg::Any::Resources => op_resources,
      msg::Any::Run => op_run,
      msg::Any::RunStatus => op_run_status,
      msg::Any::SetEnv => op_set_env,
      msg::Any::Shutdown => op_shutdown,
      msg::Any::Start => op_start,
      msg::Any::Stat => op_stat,
      msg::Any::Symlink => op_symlink,
      msg::Any::Truncate => op_truncate,
      msg::Any::WorkerGetMessage => op_worker_get_message,
      msg::Any::WorkerPostMessage => op_worker_post_message,
      msg::Any::Write => op_write,
      msg::Any::WriteFile => op_write_file,
      msg::Any::Now => op_now,
      msg::Any::IsTTY => op_is_tty,
      msg::Any::Seek => op_seek,
      msg::Any::Permissions => op_permissions,
      msg::Any::PermissionRevoke => op_revoke_permission,
      _ => panic!(format!(
        "Unhandled message {}",
        msg::enum_name_any(inner_type)
      )),
    };
    op_creator(&isolate, &base, data)
  };

  // ...省略多余的代码
}

在每個類型的函數中會根據在Typescript中呼叫libdeo.send方法時傳入的sync參數值去判斷同步執行還是非同步執行。

let (is_sync, op) = dispatch(isolate, control_buf, zero_copy_buf);
同步執行

在執行dispatch方法後,會傳回is_sync的變量,如果is_sync為true,表示方法是同步執行的,op表示傳回的結果。 rust程式碼會呼叫c 檔案api.cc中的deno_respond方法,將執行結果同步回去,deno_respond方法中根據current_args_的值去判斷是否為同步訊息,如果current_args_存在值,則直接傳回結果。

非同步執行

在deno中,執行非同步操作是透過rust的Tokio模組來實現的,在呼叫dispatch方法後,如果是非同步操作,is_sync的值為false,op不再是執行結果,而是一個執行函數。透過tokio模組派生一個線程程異步去執行該函數。

    let task = op
      .and_then(move |buf| {
        let sender = tx; // tx is moved to new thread
        sender.send((zero_copy_id, buf)).expect("tx.send error");
        Ok(())
      }).map_err(|_| ());
    tokio::spawn(task);

在deno初始化時,會建立一個管道,程式碼如下:

let (tx, rx) = mpsc::channel::<(usize, Buf)>();

管道可以實現不同執行緒之間的通信,由於非同步操作是創建了一個新的執行緒去執行的,所以子執行緒無法直接和主執行緒之間通信,需要透過管道的機制去實現。在非同步程式碼執行完成後,呼叫tx.send方法將執行結果加入管道裡面,event loop會每次從管道裡面去讀取結果回傳。

Event Loop

由於非同步操作依賴事件循環,所以先解釋一下deno中的事件循環,其實事件循環很簡單,就是一段循環執行的程式碼,當達到條件後,事件迴圈會結束執行,deno中主要的事件循環程式碼實作如下:

pub fn event_loop(&self) -> Result<(), JSError> {
    // Main thread event loop.
    while !self.is_idle() {
      match recv_deadline(&self.rx, self.get_timeout_due()) {
        Ok((zero_copy_id, buf)) => self.complete_op(zero_copy_id, buf),
        Err(mpsc::RecvTimeoutError::Timeout) => self.timeout(),
        Err(e) => panic!("recv_deadline() failed: {:?}", e),
      }
      self.check_promise_errors();
      if let Some(err) = self.last_exception() {
        return Err(err);
      }
    }
    // Check on done
    self.check_promise_errors();
    if let Some(err) = self.last_exception() {
      return Err(err);
    }
    Ok(())
  }

self.is_idle方法用來判斷是否所有的非同步運算都執行完畢,當所有的非同步操作都執行完畢後,停止事件循環,is_idle方法程式碼如下:

fn is_idle(&self) -> bool {
    self.ntasks.get() == 0 && self.get_timeout_due().is_none()
  }

當產生一次非同步方法呼叫時,會呼叫下面的方法,使ntasks內部的值加1,

fn ntasks_increment(&self) {
    assert!(self.ntasks.get() >= 0);
    self.ntasks.set(self.ntasks.get() + 1);
  }

在event loop循環中,每次從管道中去取值,這裡event loop充消費者,執行非同步方法的子線程充當生產者。如果在一次事件循環中,取得到了一次執行結果,那麼會呼叫ntasks_decrement方法,使ntasks內部的值減1,當ntasks的值為0的時候,事件循環會退出執行。在每次循環中,將管道中取得的值作為參數,呼叫complete_op方法,將結果傳回。

rust中将异步操作结果返回回去

在初始化v8实例时,绑定的c++方法中有一个Recv方法,该方法的作用时暴露一个Typescript的函数给rust,在deno的io.ts文件的start方法中执行libdeno.recv(handleAsyncMsgFromRust),将handleAsyncMsgFromRust函数通过c++方法暴露给rust。具体实现如下:

export function start(source?: string): msg.StartRes {
  libdeno.recv(handleAsyncMsgFromRust);

  // First we send an empty `Start` message to let the privileged side know we
  // are ready. The response should be a `StartRes` message containing the CLI
  // args and other info.
  const startResMsg = sendStart();

  util.setLogDebug(startResMsg.debugFlag(), source);

  setGlobals(startResMsg.pid(), startResMsg.noColor(), startResMsg.execPath()!);

  return startResMsg;
}

当异步操作执行完成后,可以在rust中直接调用handleAsyncMsgFromRust方法,将结果返回给Typescript。先看一下handleAsyncMsgFromRust方法的实现细节:

export function handleAsyncMsgFromRust(ui8: Uint8Array): void {
  // If a the buffer is empty, recv() on the native side timed out and we
  // did not receive a message.
  if (ui8 && ui8.length) {
    const bb = new flatbuffers.ByteBuffer(ui8);
    const base = msg.Base.getRootAsBase(bb);
    const cmdId = base.cmdId();
    const promise = promiseTable.get(cmdId);
    util.assert(promise != null, `Expecting promise in table. ${cmdId}`);
    promiseTable.delete(cmdId);
    const err = errors.maybeError(base);
    if (err != null) {
      promise!.reject(err);
    } else {
      promise!.resolve(base);
    }
  }
  // Fire timers that have become runnable.
  fireTimers();
}

从代码handleAsyncMsgFromRust方法的实现中可以知道,首先通过flatbuffer反序列化返回的结果,然后获取返回结果的cmdId,根据cmdId获取之前创建的promise对象,然后调用promise.resolve方法触发promise.then中的代码执行。

以上是deno通訊實作的方法(附程式碼)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:segmentfault.com。如有侵權,請聯絡admin@php.cn刪除