为什么说 WebAssembly 属于浏览器之外? Why WebAssembly Belongs Outside the Browser

Posted sp42a

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了为什么说 WebAssembly 属于浏览器之外? Why WebAssembly Belongs Outside the Browser相关的知识,希望对你有一定的参考价值。

Why WebAssembly Belongs Outside the Browser
原文 https://www.wasm.builders/thomastaylor312/why-webassembly-belongs-outside-the-browser-331a

作为三个不同的 WebAssembly(Wasm)创业公司的员工,以及大型的开源 Wasm 项目的创建者/维护者,我们在社区看到很多关于为什么人们会选择 Wasm 的问题。有时它是一个问题,即这是否只是在重复我们过去尝试过的同样的事情,而其他时候它更像是 “好吧,反正我在云Linux服务器上做所有事情,那么我为什么要开始使用这个?” 为了回答我们看到的许多问题,我们认为合作写一篇博文是一个好主意,在那里我们讨论为什么 Wasm 是如此强大和有用。但在我们得到这些答案之前,我们需要从了解一点历史开始。

As employees of 3 different WebAssembly (Wasm) startups and creators/maintainers of some of the largest open source Wasm projects, we’ve been seeing a lot of questions in our communities about why people would choose Wasm. Sometimes it is a question of whether this is just repeating the same things we tried in the past and other times it is more along the lines of “well, I do everything on cloud linux servers anyway, so why should I start using this?” In order to answer many of the questions we see, we thought it would be a good idea to collaborate on a blog post where we address why Wasm is so powerful and useful. But before we get to those answers, we need to start with a little history

A Brief History of Wasm

015 年,卢克·瓦格纳(Luke Wagner)在 Mozilla 博客上发表了一篇声明:

In 2015, Luke Wagner made an announcement on his Mozilla blog:

我很高兴地报告,我们在 Mozilla 开始与 Chromium、Edge 和 WebKit 工程师合作,创建一个新的标准 WebAssembly,该标准定义了一种便携式、大小和加载时间高效的格式和执行模型,专门设计为 Web 的编译目标。
I’m happy to report that we at Mozilla have started working with Chromium, Edge and WebKit engineers on creating a new standard, WebAssembly, that defines a portable, size- and load-time-efficient format and execution model specifically designed to serve as a compilation target for the Web.

构建 WebAssembly 的团队开始了两个主要目标:

With that, the group building WebAssembly set out to achieve two major objectives:

  • 建立一种二进制编译目标的规范,可以在浏览器中运行。Build a specification for a binary compilation target that could run in the browser
  • 获得所有主要浏览器的支持。Gain support from all major browsers

在几年内,构建 Wasm 的团队已经实现了这两个目标。在 W3 的指导下,Core Wasm 规范达到了推荐状态。并且所有主要浏览器都包括了对它的支持。

In a few years, the team building Wasm had achieved both. Under the auspices of W3, a Core Wasm specification reached Recommendation status. And all major browsers included support.

但为了 WebAssembly 能够成功,语言必须能够编译成 WebAssembly。一些语言很快就跟上了,C/C++ 和 Rust 领先。在卢克最初的帖子发布几年后,现在许多语言都支持 WebAssembly。

But for WebAssembly to be successful, languages must be able to compile to WebAssembly. Some languages came along quickly, with C/C++ and Rust leading the way. Now, several years after Luke’s initial post, many languages have WebAssembly support.

WebAssembly 在浏览器世界中取得了成功,拥有像 Adobe 和 Figma 这样的大规模采用者。但是其他人已经注意到了 WebAssembly 在浏览器上下文之外的优点。

WebAssembly has enjoyed success in the browser world, with large-scale adopters like Adobe and Figma. But others have noticed WebAssembly’s virtues beyond the browser context.

许多非浏览器运行时,如 Wasmtime、Wamr、Wasm3、WasmEdge 和 Wasmer 将 WebAssembly 格式应用于浏览器之外的特定用例。这些工具展示了规范的灵活性,一些实现,例如 Wasm3 作为解释器执行,而其他运行时则支持 JIT 和 AOT 编译以及缓存和优化功能。

A host of non-browser runtimes like Wasmtime, Wamr, Wasm3, WasmEdge, and Wasmer take the WebAssembly format and apply it to specific use cases beyond the browser. And these tools show the flexibility of the specification, with some implementations like Wasm3 executing as an interpreter, while other runtimes support JIT and AOT compiling as well as caching and optimization features.

虽然在浏览器中的 WebAssembly 通常依赖于 javascript 和 Wasm 运行时之间的桥接,但非营利性字节码联盟(其中 Cosmonic、Fermyon 和 Suborbital 都是成员)最近的工作集中在添加系统绑定上。WebAssembly 系统接口(WASI)是其中一个很好的例子,它增加了与系统资源(例如文件系统、环境变量、时钟和随机数生成器)交互的标准支持。

While WebAssembly in the browser typically relies on bridges between JavaScript and the Wasm runtime, recent work by the non-profit Bytecode Alliance (of which Cosmonic, Fermyon, and Suborbital are all members) focuses on adding system bindings. The WebAssembly System Interface (WASI) is a good example of this, adding standardized support for interacting with system resources such as file systems, environment variables, clocks, and random number generators.

如今的新兴标准能够使 WebAssembly 可以在浏览器之外使用。但是它在浏览器之外是不是有吸引力呢?我们认为是的。实际上,我们认为 WebAssembly 更适合在云上跑而非在浏览器里面跑。

Today’s nascent standards make WebAssembly usable beyond the browser. But is it desirable outside of the browser? We think so. In fact, we think that the very properties that make it good for the browser are what make it even more compelling as a target for the cloud.

浏览器上不错,云上更佳 Good for the browser, great for the cloud

对于 Web 浏览器里的运行时语言,需要某些特质才行。而这些特质,对于云上而言,也是非常重要的。

There are several characteritics that are necessary for a language runtime in the web browser. These same characteristics, though, are also attractive in the cloud.

  • 安全性:如果你想在浏览器里运行可信的代码,你要在隔离区运行。这跟云的一样。Security: If you are going to run untrusted code in the browser, you want to make sure it is running in isolation. The same is true in the cloud.
  • 跨平台/跨架构:我们写浏览器的代码,自然是跨平台的。在云上也是一样。Cross-platform/Cross-arch: When we build code for the browser, we want to write it once and have it run anywhere. This is also a highly desirable feature for the cloud.
  • 多语言支持:WebAssembly 其中一个宏伟的目标就是支持多语言。云上哪只有 JS 跑的啊?肯定要多语言的。Polyglot: A big goal of the WebAssembly project was to extend the browser to many languages. Cloud development is not as JS-centric as browser development. Multi-langauge support is not optional for us.
  • 运行速度:没人愿意等网页太久。同样道理在云上也是,不过换成调整的可伸缩性的场景。Speed: Nobody wants to wait for a web page to load. The same is true on cloud. Instant loading means rapid scaling.
  • 运行效率 Efficiency: Browsers are constrained in how much energy they can consume. On the cloud, the more efficient the runtime, the cheaper it is to operate.
    体积大小 Size: Before we can talk about startup speed in the browser, we have to talk about download speed. And that is largely a function of the objects we download. Smaller binaries mean faster download. And in the cloud, that translates to the ability to move these objects around the cloud.

现在我们深入挖掘一下有什么优秀的特点。

Now let’s dive into how these properties are important in practice.

安全问题 Security

运行云计算软件的一个更令人困惑的方面是了解其安全属性、攻击面,以及如何保持你的组织安全。最近,供应链安全漏洞的趋势和未打补丁的操作系统的漫长历史道路,使公司在安全问题上花费了数十亿美元和无法估量的时间损失。Wasm 的主要目标之一是提供一个简单的、容易理解的表面区域,以确保代码可以在沙盒内执行,说明攻击者可能从外到内、从内到外伤害你的基础设施的所有方式。WebAssembly 迫使在其沙盒内运行的代码与沙盒外的操作系统之间的互动被明确定义,并非常细化地启用。在高层次上,这意味着 Wasm 字节码试图执行的每一个 “系统调用”,都由运行时给定的一组函数处理。这意味着如果你想禁止文件系统访问,网络访问,甚至是对系统时钟的访问,你可以通过改变可用的主机函数集来实现。将这一点与线性、边界检查的程序内存结合起来,你就可以得到一个执行任意的、不受信任的代码的容器,它在简单性和可攻击的表面积轴上超过了虚拟机和容器的安全模型。

One of the more perplexing aspects of running cloud software is understanding its security properties, attack surface, and how to keep your organization safe. A recent trend of supply-chain security vulnerabilities and a long, historic road of unpatched operating systems has cost companies billions of dollars and immeasurable lost time to security issues. One of the key goals of Wasm is to provide a simple, easily understood surface area to ensure code can be executed inside a sandbox that accounts for all the ways attackers could harm your infrastructure from outside-in, and inside-out. WebAssembly forces the interactions between the code running within its sandbox, and the operating system outside the sandbox to be explicitly defined and enabled very granularly. At a high level, this means that every “system call” that Wasm bytecode attempts to perform is handled by a set of functions given to the runtime when it starts up. This means if you want to disable filesystem access, network access, or even access to the system clock, you can do so by changing the set of host functions available. Combine this with linear, bounds-checked program memory, and you arrive at a vessel for executing arbitrary, untrusted code that surpasses the security models of VMs and containers on the axes of simplicity and attack-able surface area.

在现实世界中,这相当于一个执行环境,允许操作者更自信地执行不受信任的代码。这可能是未经审核的第三方依赖,或用户提交的代码,如插件和用户定义函数(UDF)的形式。如果用户有能力上传旨在扩展你的软件的代码片段,那么在当前基于容器的平台上运行这些代码是相当令人生畏的,因为他们有相当大的余地来接触和探测你的内部基础设施。另外,考虑到用于执行用户代码的容器基础镜像很可能包含漏洞,当数百、数千或更多的用户提供的容器需要用修补过的操作系统重新构建时,会造成巨大的头痛。通过消除运行程序的大部分 "类似操作系统 "的方面,WebAssembly 提供了一个更加可控和可理解的基础,在此基础上建立安全环境来运行代码。

In the real world, this amounts to an execution environment that allows operators to more confidently execute untrusted code. This can come in the form of un-audited third party dependencies, or user-submitted code such as plugins and User-Defined Functions (UDFs). If users are given the ability to upload snippets of code meant to extend your software, it’s pretty daunting to run that code on current container-based platforms, as they are given quite a lot of leeway to reach out and prod around your internal infrastructure. Also consider the container base images used to execute user code could very well contain vulnerabilities, causing a huge headache when hundreds, thousands, or more user-provided containers need to be re-built with patched OSs. By removing most of the “OS-like” aspects from running a program, WebAssembly provides a much more controllable and understandable base upon which to build secure environments to run code.

跨平台/跨架构 Cross-platform/Cross-arch

WebAssembly 最引人瞩目的特性可能是它完全不受平台和架构的限制。然而,这远远超出了大多数人想到的 JVM 过去的尝试:“编译一次,到处运行”。是的,Wasm 有潜力真正实现“编译一次,到处运行”,但这并不仅仅是 WebAssembly 真正优越的地方。在这方面最好的例子是组件模型。组件模型允许开发人员编写代码并将其导出为接口。例如,您可能想使用一个密钥存储库。密钥存储库的接口可能是这样的:

Possibly the most touted feature of WebAssembly is that it is entirely platform and architecture agnostic. However, this goes way beyond what most people think of with technologies such as the JVM or other “compile once, run anywhere” attempts of the past. Yes, Wasm has the potential to truly compile once and run anywhere, but that is not where the real power of WebAssembly shines. There is no better example of this than the Component Model. The Component Model allows developers to write code and export their APIs as interfaces. For example, you could be wanting to use a key store. An interface for a key store could look like this:

set: func(key: string, value: payload, ttl: option<u32>) -> expected<unit, error>

get: func(key: string) -> expected<payload, error>

delete: func(key: string) -> expected<unit, error>

如果我们想实现一个密钥存储库,我们可以用任何一种语言(在这个例子中,假设我们使用 Go)编写它,只要我们按照这个接口导出即可。然后,其他想要使用我们实现的密钥值存储的开发人员可以用完全不同的语言编写他们的代码,但仍然能够使用我们之前在 Go 中编写的密钥值实现。基本上这给了我们一个通用的库或依赖项注册表,可以根据每个人的用例进行组合。因此,您不需要为每种语言编写单独的客户端库,只需编写一次并与另一个完全不同的语言组合即可。这意味着共享和协作变得更加容易,无论语言、平台或架构如何!如果您感到好奇并想了解更多,我们几个人写了一些详细的博客文章,如果您想阅读更多有关组件模型的信息,可以参考这些文章

If we wanted to implement a key store, we could write it in any language (let’s say Go for this example) we want to that compiles to a Wasm module as long as we export to this interface. Then, another developer elsewhere who wants to consume our implementation could write their code in an entirely different language, but still be able to consume the key value implementation we wrote in Go earlier. Essentially, this gives us a universal library or registry of dependencies that can be composed together as needed for each person’s use case. So, instead of needing a separate client library for every single language, you could write it once and then compose it together with something in an entirely different language. This means it is much more easy to share and collaborate, no matter the language, platform or architecture! If you are curious and want to learn more, several of us have written some detailed blog posts about the component model if you want to read more about it.

除了 Wasm 跨平台/跨架构支持提供的可组合性之外,还具有成为后 Kubernetes 世界构建的运行时的能力。我们知道这是一个大胆的说法,但请跟着我们的思路走。人们很快意识到 Kubernetes(和容器)的局限性。尽管我们喜欢假装容器可以“运行在任何地方”,但我们知道这并不是真的。要支持不同的平台,您需要为每个平台+架构组合构建不同的映像。而且,容器是一种 Linux 技术。是的,一些非常聪明的人为 Windows 添加了容器,但这是一组完全不同的技术(它无法运行 Linux 容器,也不能使常规容器平台运行 Windows 容器)。此外,容器运行时的开销(特别是在运行 Kubernetes 时)会阻止容器在边缘处的效果。除此之外,需要针对越来越多的定制处理器。 对此 Wasm 是一个完美的解决方案,因为它既是跨平台和架构无关的,而且体积小(有关更多信息,请参见下面关于尺寸的部分!)。你能够拥有在巨大的云服务器和靠近用户的小型边缘设备上运行的代码,而不需要重新编译。

我们认识到并感激容器提供的促进因素,以帮助人们过渡到云端,但我们也坚信 Wasm 的后 Kubernetes 未来。

Beyond the composibility offered by the cross platform/arch support of Wasm is the power to be a runtime that is purpose-built for a post-Kubernetes world. We know that is a bold claim, but stick with us here. People have quickly realized that Kubernetes (and containers) can only be stretched so far. As much as we like to pretend that containers can “run anywhere,” if we are being honest with ourselves, we know that is not true. To support different platforms, you need to build a different image for each platform + arch combination. Also, containers are a Linux technology. Yes, some very smart people added containers for Windows, but it is an entirely different set of technology (and it can’t run Linux containers, nor can normal container platforms run Windows containers). Also, the overhead of a container runtime (particularly when running Kubernetes) prevents containers from being effective the further out towards the edge you get. On top of this, there are an ever increasing number of custom processors that need to be targeted. Wasm is a perfect solution for this as it is platform and architecture agnostic as well as being small (see the section on Size below for more!). You are able to have code that runs both on huge cloud servers and tiny edge devices close to your users without any recompilation needed.

We acknowledge and are grateful for the forcing factor that containers provided to help people transition to the cloud, but we are also firm believers in the post-Kubernetes future of Wasm.

支持多语言 Polyglot

正如我们在前一节中提到的,Wasm 的另一个重要特性是它是支持多语言的。因为 Wasm 是一个编译目标,所以使用它不需要特别的设置。唯一需要做的只是让那门语言增加针对 Wasm 的编译即可。有些语言会比其他语言更快地采用这种技术,但我们已经看到许多语言已经或开始进行这项工作了。因此,您可以使用不同的语言来编写同一个应用程序的不同部分,而不仅仅是同一服务(请参见前一节中的组件模型示例)!

As we alluded to in the previous section, one of the other key features of Wasm is that it is polyglot. Because Wasm is a compile target, there is no special buy in required to use it. All that needs to happen is that a language adds support for compiling to Wasm. Some languages are going to adopt that sooner than others, but we are already seeing that many languages have already done or started that work. Because of this, you can have different parts of the same application, not just the same service, be written in different languages (see the component model example in the previous section)!

接下来,我们将提出另一项大胆的主张,即 Wasm 有潜力成为我们最后一个插件模型。目前为工具写插件,几乎就是一件麻烦的事情。您必须用相同的语言编写,设置某种通信协议(如 gRPC),或者运行其他二进制文件并使用某种约定的 stdin/stdout 协议。所有这些选项都是限制性的和/或效率低下的。使用 Wasm 的话,插件可使用任何语言编写并编译为 Wasm。然后该 Wasm 模块可以作为其他语言插件模型的一部分去执行——不需要加壳或跨进程通信。除此之外,您还可以获得下面我们要说的几项优势,包括运行速度和体积大小的优势。

We’ll follow that up with another bold claim that we think Wasm has the potential to be the last plugin model we’ll ever need. Currently, writing a plugin for almost any tool is almost guaranteed to be a pain. You either have to write in the same language, set up some sort of communication protocol (like gRPC), or shell out to another binary with some sort of agreed upon stdin/stdout contract. All of these options are confining and/or inefficient. With Wasm, a plugin could be written in any language and compiled to Wasm. That Wasm module can then be executed by any other language as part of a plugin model – no shelling out or cross-process communication needed. On top of that, you get the advantages of speed and size discussed below.

运行速度 Speed

VM 和容器是公共云成为可能的关键。正如我们几次提到的那样,这些都是非常好的技术,在计算领域中有其地位,但不是可满足世界上所有云需求的万能药。在资源受限或极高可用情况的情况下运行代码(例如边缘计算,物联网或巨大的数据处理集群),VM 和容器实际上可能会阻碍我们从硬件中榨取极大性能的能力。由于在许多情况下,我们可以获得与 WebAssembly 相同(或更高)的隔离保证,因此可以消除 VM 和容器的底层“公共云安全网”,以更好地利用我们的服务器和设备来跑程序。由于 Wasm 是一个编译技术,可支持任何硬件架构和任何操作系统的低级字节码,因此我们可以(并要这样!)直接在裸机上运行 Wasm。这允许将工作负载更紧密地打包到可用的硬件上,以至于在性能、能源、环境影响等方面具有着巨大的影响。

The key enabling technologies that made public cloud possible were VMs and containers. As we’ve touched on a few times, these are great technologies that have their place in the world of computing, but they are not a magic bullet that can make all of the world’s cloud needs viable. When running code in resource-constrained or extremely high-usage scenarios such as edge computing, IoT, or gigantic data processing clusters, VMs and containers can actually hamper our ability to get maximum performance out of our hardware. Since we get the same (or higher) isolation guarantees from WebAssembly in many cases, we can remove the underlying “public cloud safety nets” of VMs and containers to take better advantage of the servers and devices our code is running on. Since Wasm is a low-level bytecode that can be compiled to support any hardware architecture and any OS, we can (and should!) run Wasm directly on bare metal. This allows workloads to be packed much more tightly onto the available hardware, and it has huge impacts in terms of performance, energy usage, environmental impact, etc.

这些性能优势在高度短暂的工作负载(例如云函数)中尤为明显。Wasm 运行时和它加载的代码,通常比等效的容器镜像或虚拟机小一个数量级(甚至更多),因此它们可以更快地启动和终止,并具有更高的复制量。在许多云部署中,这些是极其可取的优势,它部署的软件能够更灵活地处理流量峰值,并扩展以处理更高的总流量。由于 WebAssembly 模块实际上只是一个单独的程序,而不是扮演操作系统角色的容器或虚拟机,主机操作系统的控制和硬件优化可以更有效地利用多核架构,同时保持强大的隔离。

These performance benefits are especially evident in highly ephemeral workloads such as cloud functions. Since a Wasm runtime and the code it’s loading is usually an order of magnitude (or more) smaller than an equivalent container image or VM, they can start up and terminate much more quickly with a higher amount of replication. These are extremely desireable properties in many kinds of cloud deployments, as it allows deployed software to more nimbly handle spikes in traffic as well as scale out further to handle higher total amounts of traffic. Since a WebAssembly module is effectively just a single program, rather than a container or VM which plays the role of an operating system, the host OS’s controls and hardware optimizations can more effectively take advantage of multi-core architectures while maintaining strong isolation.

大小和效率 Size and Efficiency

在当今的主导的场景中,我们过度消耗云资源。我们提供足够的副本以满足峰值负载要求,而这些副本则无所事事地消耗资源大部分时间。并且,因为我们优化的是最高需求,所以我们分配的 CPU、内存和存储比通常需要的要多,仅仅是为了准备应对流量峰值。我们必须做好准备,因为当今的解决方案不能快速扩展。

In today’s dominant paradigms, we overconsume cloud resources. We provision enough replicas to meet peak load requirements, and those replicas sit idly consuming resources most of the time. And again, because we are optimizing for highest possible demand, we allocate more CPU, memory, and storage than we typically need simply in order to be prepared for traffic spikes. And we must be prepared because today’s solutions cannot quickly scale up.

WebAssembly的大小和效率意味着可伸缩性的成本不需要太昂贵。我们几乎可以实时地扩展,然后又轻松地缩小。我们可以在数据中心或集群中安装一致的小型 WebAssembly 模块,在需要时才执行它们。因此我们可以在不实际运行的情况下廉价地实现高可用集群。

WebAssembly’s size and efficiency means scaling is not costly. We can scale up nearly instantly… and then scale back down with ease. We can install the same small WebAssembly modules throughout our datacenters or clusters, but not execute them until demand is there. As a result, we can cheaply achieve high replica counts without actually running until necessary.

并且,由于 JIT/AOT 运行时已经准备就绪,我们可以确保我们的 WebAssembly 二进制文件已预先优化执行,从而减少能源和资源消耗。

And with JIT/AOT runtimes readily at hand, we can make sure that our WebAssembly binaries are pre-optimized for execution, cutting down energy and resource consumption.

在许多情况下,由于我们不必携带大量的系统库和文件构件,我们处理的对象的大小比容器小得多。

In many cases, since we don’t have to cart around a plethora of system libraries and file artifacts, the sizes of the objects we are dealing with are considerably smaller than containers.

综上所述,WebAssembly 在云中拥有令人信服的特点:它比其他云服务运营更便宜。

Combined, all of these point toward a compelling feature of WebAssembly in the cloud: It is cheaper to operate than other cloud services.

总结 Wrapping up

读毕此文你可能感到,我们对 WebAssembly 所提供的众多可能性感到兴奋!当然,我们知道这一切都是全新的,还需要很多工作要做。这就是你阅读此文的原因。亲爱的读者,你能做点什么呢?最好的事情之一就是参与 Wasm 社区,并动手建立一些东西。我们的项目,Spin, Sat, 和wasmCloud,这些都是开始很好的选择,却不是唯一的选择。无论你做什么,请与社区分享你建立的东西,并让我们知道有什么差距,以便我们能够朝着未来继续前进!

As you can probably tell, we are excited about the many possibilities WebAssembly affords. However, we know that this is all new and lots of work is still needed. This is where you come in! One of the best things you can do is get involved with the Wasm community and to try building things. Our projects, Spin, Sat, and wasmCloud are good places to get started, but are far from the only projects. Whatever you do, please share what you build with the community and let us know what the gaps are so we can continue to build towards the future.

以上是关于为什么说 WebAssembly 属于浏览器之外? Why WebAssembly Belongs Outside the Browser的主要内容,如果未能解决你的问题,请参考以下文章

Shopify如何在浏览器之外使用WebAssembly?

WebAssembly-wasm

通过漫画介绍WebAssembly

为什么我说WebAssembly是区块链计算的未来

吃饭的时候看到说WebAssembly成为W3C标准,于是好奇查了查相关文章

说说WebAssembly