WASM 运行时

WASM 运行时使用同一套 capability 协议。差异在于入口函数和宿主桥接:网络、HostGateway 和响应读取都通过 ting_env 导入函数完成。

入口形态

推荐编译到 wasm32-unknown-unknown。运行时根据 capability 的 invoke 字段调用导出的 invoke 方法,并传入方法名和 JSON 参数。

#[no_mangle]
pub extern "C" fn invoke(method: *const i8, params: *const i8) -> *mut i8 {
    let method = read_c_string(method);
    let params = read_c_string(params);

    match method.as_str() {
        "documentInvoke" => document_invoke(&params),
        "searchMetadata" => search_metadata(&params),
        _ => error_json("unknown method"),
    }
}

Host functions

http_request 用于受权限控制的网络访问;host_invoke 调用 HostGateway;host_response_sizehost_read_body 读取宿主返回的 JSON 响应。

#[link(wasm_import_module = "ting_env")]
extern "C" {
    fn http_request(
        method_ptr: *const u8,
        method_len: i32,
        url_ptr: *const u8,
        url_len: i32,
        body_ptr: *const u8,
        body_len: i32,
    ) -> i32;

    fn host_invoke(
        method_ptr: *const u8,
        method_len: i32,
        params_ptr: *const u8,
        params_len: i32,
    ) -> i32;

    fn host_response_size(handle: i32) -> i32;
    fn host_read_body(handle: i32, ptr: *mut u8, len: i32) -> i32;
}

能力示例

WASM 很适合 content_processormetadata_provider 和计算型 tool_provider。下面是文档处理插件的 capability 声明。

runtime: wasm
entry_point: document_reader.wasm
capabilities:
  - id: document.reader
    kind: content_processor
    invoke: documentInvoke
    matches:
      extensions: [txt, pdf]
    operations:
      - probe
      - extract_metadata
      - list_sections
      - read_chunk
      - render_page
permissions:
  - type: media_read
  - type: cache_write

打包

包内放置 plugin.yml 和编译后的 .wasm。如果 WASM 需要网络或 HostGateway,manifest 中仍要声明对应权限。

trpack validate my-plugin
trpack build my-plugin --output dist/my-plugin.tr
trpack verify dist/my-plugin.tr

适合 WASM 的场景

  • 跨平台文本、PDF 或自定义文档格式解析。
  • 需要 Rust 生态库但不依赖系统动态库的内容处理。
  • 较重的计算任务,例如分段、索引、压缩或格式探测。