golang基于WebAssembly构建函数、微服务和单体应用的插件框架Tarmac的使用

Golang基于WebAssembly构建函数、微服务和单体应用的插件框架Tarmac的使用

Tarmac简介

Tarmac是一种新的应用程序框架方法,它语言无关,并提供对BoltDB、Redis和Cassandra等键值存储,MySQL和Postgres等传统SQL数据库,以及相互TLS认证和可观测性等基本功能的支持。

支持Go、Rust和Zig等语言,您可以使用自己喜欢的语言编写函数,同时受益于构建现代分布式服务的强大功能套件。

Tarmac Banner

快速开始

Tarmac使得构建复杂函数变得简单。下面的Go函数是一个很好的示例:

// Tac是一个小型、简单的Go程序,是Tarmac的WASM模块示例。该程序将接受Tarmac
// 服务器请求,记录它,并将负载反向回显。
package main

import (
	"fmt"
	"github.com/tarmac-project/tarmac/pkg/sdk"
)

var tarmac *sdk.Tarmac

func main() {
	var err error

	// 初始化Tarmac SDK
	tarmac, err = sdk.New(sdk.Config{Handler: Handler})
	if err != nil {
		return
	}
}

// Handler是自定义的Tarmac Handler函数,它将接收一个负载并
// 必须返回一个负载和一个nil错误。
func Handler(payload []byte) ([]byte, error) {
	var err error

	// 记录它
	tarmac.Logger.Trace(fmt.Sprintf("Reversing Payload: %s", payload))

	// 检查缓存
	key := string(payload)
	rsp, err := tarmac.KV.Get(key)
	if err != nil || len(payload) < 1 {
		// 翻转并反转
		if len(payload) > 0 {
			for i, n := 0, len(payload)-1; i < n; i, n = i+1, n-1 {
				payload[i], payload[n] = payload[n], payload[i]
			}
		}
		rsp = payload

		// 存储在缓存中
		err = tarmac.KV.Set(key, payload)
		if err != nil {
			tarmac.Logger.Error(fmt.Sprintf("Unable to cache reversed payload: %s", err))
			return rsp, nil
		}
	}

	// 返回负载
	return rsp, nil
}

要开始运行此函数,导航到我们的示例目录并运行make build命令。make build命令编译代码并生成一个WebAssembly模块。

$ cd example/tac/go
$ make build

编译完成后,您可以使用以下Docker命令将此函数作为独立微服务运行:

$ docker run -p 8080:8080 \
  -e "APP_ENABLE_TLS=false" -e "APP_LISTEN_ADDR=0.0.0.0:8080" \
  -v `pwd`/functions:/functions madflojo/tarmac

Tarmac现在运行后,我们可以使用任何HTTP客户端(如curl)访问我们的WASM函数。

$ curl -v --data "Tarmac Example" http://localhost:8080

就是这样!您可以使用Tarmac用Go、Rust、AssemblyScript、Swift或Zig编写和部署函数。

多函数服务

虽然Tarmac用户可以快速构建具有单一功能的独立微服务,但它更擅长多函数服务。Tarmac运行多个函数的能力意味着您可以创建具有无服务器函数开发体验的专用平台。

要开始使用多函数服务,您需要提供一个tarmac.json配置文件(通过WASM_FUNCTION_CONFIG配置参数),该文件列出了要加载的函数以及要公开为端点的各种协议和路由。下面是一个示例tarmac.json配置文件:

{
  "services": {
    "my-service": {
      "name": "my-service",
      "functions": {
        "function1": {
          "filepath": "/path/to/function1.wasm"
        },
        "function2": {
          "filepath": "/path/to/function2.wasm"
        }
      },
      "routes": [
        {
          "type": "http",
          "path": "/function1",
          "methods": ["GET"],
          "function": "function1"
        },
        {
          "type": "http",
          "path": "/function2",
          "methods": ["POST"],
          "function": "function2"
        }
      ]
    }
  }
}

在多函数服务配置中,每个函数都有自己的代码库,但共享相同的服务命名空间和配置。

在上面的示例中,我们有一个名为my-service的服务,带有function1function2函数。每个函数在/path/to/function1.wasm/path/to/function2.wasm都有一个.wasm文件。

要为每个函数定义路由,请向路由数组添加一个路由对象,类型设置为httpfunction设置为函数的名称。

除了http路由类型外,Tarmac还支持scheduled_task路由,该路由以特定间隔执行函数。frequency参数指定间隔(以秒为单位)。

{
  "type": "scheduled_task",
  "function": "function1",
  "frequency": 10
}

借助Tarmac对多个函数的支持,您可以通过将服务划分为更小、更易管理的部分来快速构建复杂的分布式服务。

架构

Tarmac是一个无服务器平台,使用户能够定义和执行WebAssembly函数。当Tarmac收到请求时,它会将它们转发给WebAssembly函数,这些函数充当请求处理程序。Tarmac和WebAssembly函数之间的通信通过WebAssembly过程调用(waPC)进行。

通过利用waPC,WebAssembly函数可以与Tarmac的核心功能交互。功能包括执行回调到Tarmac服务器以访问键值存储、与SQL数据库交互或向下游服务发出HTTP请求。

为了提供简化的开发人员体验,Tarmac提供了一个Go SDK,简化了waPC的使用。SDK抽象了使用waPC的复杂性,使开发人员能够专注于编写他们的函数并利用Tarmac的功能。

示例应用程序架构

下图显示了一个示例应用程序的架构。此应用程序演示了如何使用Go和Tarmac构建多函数服务。

此示例应用程序将在启动时和通过调度程序执行WebAssembly函数以管理机场数据。该应用程序还包括一个HTTP服务器,通过WebAssembly函数向客户端提供机场数据。

          +-------------------------------------------------------------------------------------------------------+                                 
          | Tarmac Host                                                                                           |                                 
          |                                       +------------------------------------------------------------+  |                                 
          |                                       | WebAssembly Engine                                         |  |                                 
          |                                       |                                                            |  |                                 
          |  +------------------------+           |  +-----------------------------------+                     |  |                                 
          |  |On Boot Function Trigger+-----------+-->Init: Creates DB Tables, Calls Load|                     |  |                                 
          |  +------------------------+           |  +--+--------------------------------+                     |  |                                 
          |                                       |     |                                                      |  |                                 
          |  +--------------------------+         |  +--v---------------------------------------------------+  |  |                                 
          |  |Scheduled Function Trigger+---------+--> Load: Calls Fetch, then loads results to SQL Database|  |  |                                 
          |  +--------------------------+         |  +--+---------------------------------------------------+  |  |                                 
          |                                       |     |                                                      |  |                                 
          |                                       |  +--v-----------------------------+                        |  |  +-----------------------------+
          |                                       |  | Fetch: Download AirportData.csv+------------------------+--+-->HTTP Server: AirportData.csv |
          |                                       |  +--------------------------------+                        |  |  +-----------------------------+
          |                                       |                                                            |  |                                 
+------+  |  +--------------------+               |  +----------------------------------+                      |  |                                 
|Client+--+-->HTTP Request Handler+---------------+-->Lookup: Fetches Data from Cache/DB|                      |  |                                 
+------+  |  +--------------------+               |  +----------------------------------+                      |  |                                 
          |                                       |                                                            |  |                                 
          |                                       +----------------------------+-------------------------------+  |                                 
          |                                                                    |                                  |                                 
          |                                                                    |                                  |                                 
          |                                                                    |                                  |                                 
          |                                       +----------------------------v-------------------------------+  |                                 
          |                                       | Tarmac Capabilities                                        |  |                                 
          |                                       |                                                            |  |                                 
          |                                       | +--------+ +------------+ +-------+ +------+               |  |                                 
          |                                       | |KV Store| |SQL Database| |Metrics| |Logger|               |  |                                 
          |                                       | +--------+ +------------+ +-------+ +------+               |  |                                 
          |                                       |                                                            |  |                                 
          |                                       +------------------------------------------------------------+  |                                 
          |                                                                                                       |                                 
          +-------------------------------------------------+-----------------------------------------------------+                                 
                                                            |                                                                                       
          +-------------------------------------------------v-----------------------------------------------------+                                 
          | External Services (Not all used in Example Application)                                               |                                 
          |                                                                                                       |                                 
          | +------+ +----------+ +-----+ +-----+ +----------+ +---------+                                        |                                 
          | |Consul| |Prometheus| |Redis| |MySQL| |PostgreSQL| |Cassandra|                                        |                                 
          | +------+ +----------+ +-----+ +-----+ +----------+ +---------+                                        |                                 
          |                                                                                                       |                                 
          +-------------------------------------------------------------------------------------------------------+                                 
语言 waPC客户端 Tarmac SDK
AssemblyScript
Go
Rust
Swift
Zig

贡献

我们非常高兴您有兴趣为Tarmac做出贡献并帮助它变得更好!要开始,请查看我们的贡献指南,了解如何提交错误报告、功能请求和代码贡献。


更多关于golang基于WebAssembly构建函数、微服务和单体应用的插件框架Tarmac的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于golang基于WebAssembly构建函数、微服务和单体应用的插件框架Tarmac的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


使用Tarmac构建Golang WebAssembly插件框架

Tarmac是一个基于WebAssembly(WASM)的Golang插件框架,允许开发者构建可扩展的函数、微服务和单体应用。下面我将详细介绍Tarmac的使用方法。

Tarmac核心概念

Tarmac的主要特点包括:

  • 基于WebAssembly运行时
  • 支持多种语言编写的插件(Golang/Rust/AssemblyScript等)
  • 轻量级且高性能
  • 提供主机调用(Host Call)能力

安装Tarmac

go get github.com/tarmac-project/tarmac

基本使用示例

1. 编写WASM插件

首先创建一个简单的Golang WASM插件:

// main.go
package main

import (
	"fmt"
)

func main() {}

//export hello
func hello(name string) string {
	return fmt.Sprintf("Hello, %s!", name)
}

编译为WASM:

tinygo build -o hello.wasm -target wasi main.go

2. 在Tarmac中加载插件

package main

import (
	"fmt"
	"log"

	"github.com/tarmac-project/tarmac/pkg/sdk"
)

func main() {
	// 初始化Tarmac
	tarmac, err := sdk.New(sdk.Config{
		Namespace: "example",
	})
	if err != nil {
		log.Fatalf("Failed to create Tarmac instance - %s", err)
	}

	// 加载WASM插件
	err = tarmac.LoadModule("hello", "hello.wasm")
	if err != nil {
		log.Fatalf("Failed to load module - %s", err)
	}

	// 调用插件函数
	result, err := tarmac.Call("hello", "hello", "World")
	if err != nil {
		log.Fatalf("Failed to call function - %s", err)
	}

	fmt.Printf("Result: %s\n", result)
}

高级功能

1. 主机调用(Host Calls)

允许WASM插件调用宿主机功能:

// 在宿主应用中注册主机函数
tarmac.RegisterHostFunction("log", func(msg string) (string, error) {
	log.Println("From WASM:", msg)
	return "Logged", nil
})

然后在WASM插件中使用:

//export logMessage
func logMessage(msg string) {
	// 调用宿主机的log函数
	_, _ = hostCall("log", msg)
}

2. 持久化存储

Tarmac提供了简单的KV存储接口:

// 在宿主应用中
store := make(map[string]string)
tarmac.RegisterHostFunction("kv_set", func(key, value string) (string, error) {
	store[key] = value
	return "OK", nil
})

tarmac.RegisterHostFunction("kv_get", func(key string) (string, error) {
	val, ok := store[key]
	if !ok {
		return "", fmt.Errorf("key not found")
	}
	return val, nil
})

3. HTTP服务集成

Tarmac可以轻松集成到HTTP服务中:

http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
	name := r.URL.Query().Get("name")
	result, err := tarmac.Call("hello", "hello", name)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.Write([]byte(result))
})

log.Fatal(http.ListenAndServe(":8080", nil))

性能优化建议

  1. 复用WASM实例:避免频繁创建和销毁WASM实例
  2. 内存管理:注意WASM内存限制,合理使用hostCall传输大数据
  3. 并发控制:Tarmac支持并发,但要注意WASM模块的线程安全性
  4. 缓存热路径:对频繁调用的函数路径进行缓存

实际应用场景

  1. 插件系统:允许用户上传自定义业务逻辑
  2. 多语言微服务:不同服务用不同语言编写,统一在Tarmac中运行
  3. 边缘计算:轻量级的WASM非常适合资源受限环境
  4. SaaS平台:为客户提供自定义业务逻辑的能力

总结

Tarmac为Golang提供了一个灵活且高性能的WASM插件框架,通过它你可以:

  • 动态加载和卸载功能模块
  • 安全地运行不受信任的代码(通过WASM沙箱)
  • 集成多种语言编写的组件
  • 构建可扩展的微服务架构

随着WebAssembly生态的成熟,Tarmac这类框架将在云原生和边缘计算领域发挥越来越重要的作用。

回到顶部