资讯专栏INFORMATION COLUMN

deno原理篇-通信实现

ChristmasBoy / 3414人阅读

摘要:理解基础篇原理篇一启动加载通信方式执行代码和相似,包含同步和异步的方式,异步方式通过的实现。同时在异步通信完成后,会创建一个对象,将作为,作为,加入中。

理解deno-基础篇
deno-原理篇一启动加载

通信方式

deno执行代码和node相似,包含同步和异步的方式, 异步方式通过async的实现。

Typescript/Javascript调用rust

在上一节中讲到deno的启动时会初始化v8 isolate实例,在初始化的过程中,会将c++的函数绑定到v8 isolate的实例上,在v8执行Javascript代码时,可以像调用Javascript函数一样调用这些绑定的函数。具体的绑定实现如下:

</>复制代码

  1. void InitializeContext(v8::Isolate* isolate, v8::Local context) {
  2. v8::HandleScope handle_scope(isolate);
  3. v8::Context::Scope context_scope(context);
  4. auto global = context->Global();
  5. auto deno_val = v8::Object::New(isolate);
  6. CHECK(global->Set(context, deno::v8_str("libdeno"), deno_val).FromJust());
  7. auto print_tmpl = v8::FunctionTemplate::New(isolate, Print);
  8. auto print_val = print_tmpl->GetFunction(context).ToLocalChecked();
  9. CHECK(deno_val->Set(context, deno::v8_str("print"), print_val).FromJust());
  10. auto recv_tmpl = v8::FunctionTemplate::New(isolate, Recv);
  11. auto recv_val = recv_tmpl->GetFunction(context).ToLocalChecked();
  12. CHECK(deno_val->Set(context, deno::v8_str("recv"), recv_val).FromJust());
  13. auto send_tmpl = v8::FunctionTemplate::New(isolate, Send);
  14. auto send_val = send_tmpl->GetFunction(context).ToLocalChecked();
  15. CHECK(deno_val->Set(context, deno::v8_str("send"), send_val).FromJust());
  16. auto eval_context_tmpl = v8::FunctionTemplate::New(isolate, EvalContext);
  17. auto eval_context_val =
  18. eval_context_tmpl->GetFunction(context).ToLocalChecked();
  19. CHECK(deno_val->Set(context, deno::v8_str("evalContext"), eval_context_val)
  20. .FromJust());
  21. auto error_to_json_tmpl = v8::FunctionTemplate::New(isolate, ErrorToJSON);
  22. auto error_to_json_val =
  23. error_to_json_tmpl->GetFunction(context).ToLocalChecked();
  24. CHECK(deno_val->Set(context, deno::v8_str("errorToJSON"), error_to_json_val)
  25. .FromJust());
  26. CHECK(deno_val->SetAccessor(context, deno::v8_str("shared"), Shared)
  27. .FromJust());
  28. }

在完成绑定之后,在Typescript中可以通过如下代码实现c++方法和Typescript方法的映射

</>复制代码

  1. libdeno.ts

</>复制代码

  1. interface Libdeno {
  2. recv(cb: MessageCallback): void;
  3. send(control: ArrayBufferView, data?: ArrayBufferView): null | Uint8Array;
  4. print(x: string, isErr?: boolean): void;
  5. shared: ArrayBuffer;
  6. /** Evaluate provided code in the current context.
  7. * It differs from eval(...) in that it does not create a new context.
  8. * Returns an array: [output, errInfo].
  9. * If an error occurs, `output` becomes null and `errInfo` is non-null.
  10. */
  11. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  12. evalContext(code: string): [any, EvalErrorInfo | null];
  13. errorToJSON: (e: Error) => string;
  14. }
  15. export const libdeno = window.libdeno as Libdeno;

在执行Typescript代码时,只需要引入libdeno,就直接调用c++方法,例如:

</>复制代码

  1. import { libdeno } from "./libdeno";
  2. function sendInternal(
  3. builder: flatbuffers.Builder,
  4. innerType: msg.Any,
  5. inner: flatbuffers.Offset,
  6. data: undefined | ArrayBufferView,
  7. sync = true
  8. ): [number, null | Uint8Array] {
  9. const cmdId = nextCmdId++;
  10. msg.Base.startBase(builder);
  11. msg.Base.addInner(builder, inner);
  12. msg.Base.addInnerType(builder, innerType);
  13. msg.Base.addSync(builder, sync);
  14. msg.Base.addCmdId(builder, cmdId);
  15. builder.finish(msg.Base.endBase(builder));
  16. const res = libdeno.send(builder.asUint8Array(), data);
  17. builder.inUse = false;
  18. return [cmdId, res];
  19. }

调用libdeno.send方法可以将数据传给c++,然后通过c++去调用rust代码实现具体的工程操作。

Typescript层同步异步实现

</>复制代码

  1. 同步

在Typescript中只需要设置sendInternal方法的sync参数为true即可,在rust中会根据sync参数去判断是执行同步或者异步操作,如果sync为true,libdeono.send方法会返回执行的结果,rust和typescript之间传递数据需要将数据序列化,这里序列化操作使用的是flatbuffer库。

</>复制代码

  1. const [cmdId, resBuf] = sendInternal(builder, innerType, inner, data, true);

</>复制代码

  1. 异步实现

同理,实现异步方式,只需要设置sync参数为false即可,但是异步操作和同步相比,多了回掉方法,在执行异步通信时,libdeno.send方法会返回一个唯一的cmdId标志这次调用操作。同时在异步通信完成后,会创建一个promise对象,将cmdId作为key,promise作为value,加入map中。代码如下:

</>复制代码

  1. const [cmdId, resBuf] = sendInternal(builder, innerType, inner, data, false);
  2. util.assert(resBuf == null);
  3. const promise = util.createResolvable();
  4. promiseTable.set(cmdId, promise);
  5. return promise;
rust实现同步和异步

当在Typescript中调用libdeno.send方法时,调用了C++文件binding.cc中的Send方法,该方法是在deno初始化时绑定到v8 isolate上去的。在Send方法中去调用了ops.rs文件中的dispatch方法,该方法实现了消息到函数的映射。每个类型的消息对应了一种函数,例如读文件消息对应了读文件的函数。

</>复制代码

  1. pub fn dispatch(
  2. isolate: &Isolate,
  3. control: libdeno::deno_buf,
  4. data: libdeno::deno_buf,
  5. ) -> (bool, Box) {
  6. let base = msg::get_root_as_base(&control);
  7. let is_sync = base.sync();
  8. let inner_type = base.inner_type();
  9. let cmd_id = base.cmd_id();
  10. let op: Box = if inner_type == msg::Any::SetTimeout {
  11. // SetTimeout is an exceptional op: the global timeout field is part of the
  12. // Isolate state (not the IsolateState state) and it must be updated on the
  13. // main thread.
  14. assert_eq!(is_sync, true);
  15. op_set_timeout(isolate, &base, data)
  16. } else {
  17. // Handle regular ops.
  18. let op_creator: OpCreator = match inner_type {
  19. msg::Any::Accept => op_accept,
  20. msg::Any::Chdir => op_chdir,
  21. msg::Any::Chmod => op_chmod,
  22. msg::Any::Close => op_close,
  23. msg::Any::FetchModuleMetaData => op_fetch_module_meta_data,
  24. msg::Any::CopyFile => op_copy_file,
  25. msg::Any::Cwd => op_cwd,
  26. msg::Any::Dial => op_dial,
  27. msg::Any::Environ => op_env,
  28. msg::Any::Exit => op_exit,
  29. msg::Any::Fetch => op_fetch,
  30. msg::Any::FormatError => op_format_error,
  31. msg::Any::Listen => op_listen,
  32. msg::Any::MakeTempDir => op_make_temp_dir,
  33. msg::Any::Metrics => op_metrics,
  34. msg::Any::Mkdir => op_mkdir,
  35. msg::Any::Open => op_open,
  36. msg::Any::ReadDir => op_read_dir,
  37. msg::Any::ReadFile => op_read_file,
  38. msg::Any::Readlink => op_read_link,
  39. msg::Any::Read => op_read,
  40. msg::Any::Remove => op_remove,
  41. msg::Any::Rename => op_rename,
  42. msg::Any::ReplReadline => op_repl_readline,
  43. msg::Any::ReplStart => op_repl_start,
  44. msg::Any::Resources => op_resources,
  45. msg::Any::Run => op_run,
  46. msg::Any::RunStatus => op_run_status,
  47. msg::Any::SetEnv => op_set_env,
  48. msg::Any::Shutdown => op_shutdown,
  49. msg::Any::Start => op_start,
  50. msg::Any::Stat => op_stat,
  51. msg::Any::Symlink => op_symlink,
  52. msg::Any::Truncate => op_truncate,
  53. msg::Any::WorkerGetMessage => op_worker_get_message,
  54. msg::Any::WorkerPostMessage => op_worker_post_message,
  55. msg::Any::Write => op_write,
  56. msg::Any::WriteFile => op_write_file,
  57. msg::Any::Now => op_now,
  58. msg::Any::IsTTY => op_is_tty,
  59. msg::Any::Seek => op_seek,
  60. msg::Any::Permissions => op_permissions,
  61. msg::Any::PermissionRevoke => op_revoke_permission,
  62. _ => panic!(format!(
  63. "Unhandled message {}",
  64. msg::enum_name_any(inner_type)
  65. )),
  66. };
  67. op_creator(&isolate, &base, data)
  68. };
  69. // ...省略多余的代码
  70. }

在每个类型的函数中会根据在Typescript中调用libdeo.send方法时传入的sync参数值去判断同步执行还是异步执行。

</>复制代码

  1. let (is_sync, op) = dispatch(isolate, control_buf, zero_copy_buf);

</>复制代码

  1. 同步执行

在执行dispatch方法后,会返回is_sync的变量,如果is_sync为true,表示该方法是同步执行的,op表示返回的结果。rust代码会调用c++文件api.cc中的deno_respond方法,将执行结果同步回去,deno_respond方法中根据current_args_的值去判断是否为同步消息,如果current_args_存在值,则直接返回结果。

</>复制代码

  1. 异步执行

在deno中,执行异步操作是通过rust的Tokio模块来实现的,在调用dispatch方法后,如果是异步操作,is_sync的值为false,op不再是执行结果,而是一个执行函数。通过tokio模块派生一个线程程异步去执行该函数。

</>复制代码

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

在deno初始化时,会创建一个管道,代码如下:

</>复制代码

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

管道可以实现不同线程之间的通信,由于异步操作是创建了一个新的线程去执行的,所以子线程无法直接和主线程之间通信,需要通过管道的机制去实现。在异步代码执行完成后,调用tx.send方法将执行结果加入管道里面,event loop会每次从管道里面去读取结果返回回去。

Event Loop

由于异步操作依赖事件循环,所以先解释一下deno中的事件循环,其实事件循环很简单,就是一段循环执行的代码,当达到条件后,事件循环会结束执行,deno中主要的事件循环代码实现如下:

</>复制代码

  1. pub fn event_loop(&self) -> Result<(), JSError> {
  2. // Main thread event loop.
  3. while !self.is_idle() {
  4. match recv_deadline(&self.rx, self.get_timeout_due()) {
  5. Ok((zero_copy_id, buf)) => self.complete_op(zero_copy_id, buf),
  6. Err(mpsc::RecvTimeoutError::Timeout) => self.timeout(),
  7. Err(e) => panic!("recv_deadline() failed: {:?}", e),
  8. }
  9. self.check_promise_errors();
  10. if let Some(err) = self.last_exception() {
  11. return Err(err);
  12. }
  13. }
  14. // Check on done
  15. self.check_promise_errors();
  16. if let Some(err) = self.last_exception() {
  17. return Err(err);
  18. }
  19. Ok(())
  20. }

self.is_idle方法用来判断是否所有的异步操作都执行完毕,当所有的异步操作都执行完毕后,停止事件循环,is_idle方法代码如下:

</>复制代码

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

当产生一次异步方法调用时,会调用下面的方法,使ntasks内部的值加1,

</>复制代码

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

在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。具体实现如下:

</>复制代码

  1. export function start(source?: string): msg.StartRes {
  2. libdeno.recv(handleAsyncMsgFromRust);
  3. // First we send an empty `Start` message to let the privileged side know we
  4. // are ready. The response should be a `StartRes` message containing the CLI
  5. // args and other info.
  6. const startResMsg = sendStart();
  7. util.setLogDebug(startResMsg.debugFlag(), source);
  8. setGlobals(startResMsg.pid(), startResMsg.noColor(), startResMsg.execPath()!);
  9. return startResMsg;
  10. }

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

</>复制代码

  1. export function handleAsyncMsgFromRust(ui8: Uint8Array): void {
  2. // If a the buffer is empty, recv() on the native side timed out and we
  3. // did not receive a message.
  4. if (ui8 && ui8.length) {
  5. const bb = new flatbuffers.ByteBuffer(ui8);
  6. const base = msg.Base.getRootAsBase(bb);
  7. const cmdId = base.cmdId();
  8. const promise = promiseTable.get(cmdId);
  9. util.assert(promise != null, `Expecting promise in table. ${cmdId}`);
  10. promiseTable.delete(cmdId);
  11. const err = errors.maybeError(base);
  12. if (err != null) {
  13. promise!.reject(err);
  14. } else {
  15. promise!.resolve(base);
  16. }
  17. }
  18. // Fire timers that have become runnable.
  19. fireTimers();
  20. }

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

结尾

~下节讲一下deno中import的实现~

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/109084.html

相关文章

  • 理解deno-基础

    摘要:介绍是一个基于和的的安全运行时。文件中主要是的代码,是功能的具体实现。图来自于官网,图的架构图预告接下来还会有两篇文章分析的内部原理 deno介绍 deno是一个基于v8、rust和Tokio的Javascript/Typescript的安全运行时。它在内部嵌入了一个typescript的编译器。可以将typescript编译成js然后运行在v8上,并通过c++ libdeno实现js...

    heartFollower 评论0 收藏0
  • 从源码一步步学习,Ryan Dahl的Deno实现原理

    摘要:之父在中的设计错误演讲中表示不允许将任意本地函数绑定至当中。所有系统调用都将通过消息传递完成序列化。两项原生函数与。这既简化了设计流程,又使得系统更易于审计。 Node之父ry:在Node中的设计错误演讲中表示: 不允许将任意本地函数绑定至 V8 当中。 所有系统调用都将通过消息传递完成(protobuf 序列化)。 两项原生函数:send 与 recv。 这既简化了设计流程,又使得...

    goji 评论0 收藏0
  • Deno 兼容浏览器具体指的是什么?

    摘要:里面有一句描述,可以看到的目标是兼容浏览器。那么这里的兼容浏览器到底如何是什么意思呢我简单谈谈我的理解吧。很多人还有误解以为兼容浏览器指的是会提供类似里的写法。 Deno 里面有一句描述:Aims to be browser compatible,可以看到 Deno 的目标是兼容浏览器。那么这里的兼容浏览器到底如何是什么意思呢? 我简单谈谈我的理解吧。 首先这里的兼容性肯定不是 Den...

    Yangyang 评论0 收藏0
  • Deno 并不是下一代 Node.js

    摘要:长文预警字,图。开发并不是因为,也不是为了取代。不知道从官方介绍来看,可以认为它是下一代是如何脑补出来的。只是一个原型或实验性产品。所以,不是要取代,也不是下一代,也不是要放弃重建生态。的目前是要拥抱浏览器生态。 这几天前端圈最火的事件莫过于 ry(Ryan Dahl) 的新项目 deno 了,很多 IT 新闻和媒体都用了标题:下一代 Node.js。这周末读了一遍 deno 的源码,...

    mmy123456 评论0 收藏0
  • 我为 VS Code 开发了一个 Deno 插件

    摘要:自发布以来就备受关注,也有很多媒体和开发者称为下一代。所以在写这个插件之前,我又为写了一个插件。插件提供了开箱即用的支持,开发者不需要任何配置,但是有一个前提是开发者需要使用内置的。 这几天为 Deno 开发了一个 VS Code 插件:Deno support for VSCode,GitHub 地址:https://github.com/justjavac/...。 自 Deno ...

    YanceyOfficial 评论0 收藏0

发表评论

0条评论

ChristmasBoy

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<