了解 WebAssembly(WASM)模組及資料流程圖的圖定義

Azure IoT 操作 中的資料流程圖在邊緣處理遙測資料,透過一系列運算子如地圖、篩選器與分支系統進行路由。 你可以將自訂的處理邏輯打包成 WebAssembly(WASM)模組,並將它們串連成圖定義,這樣你就能轉換、過濾和豐富資料,而不必寫完整服務。

本文說明操作符類型、即時資料流模型、模組設定、主機 API 以及支撐 WASM 模組的 WIT 架構。 若要使用VS Code擴充或 dataflow-dev CLI在本地建置、測試及除錯模組,請參閱「 建構WASM模組」以了解資料流。

運算子與模組

運算元是資料流程圖中的處理單元。 每種類型都有特定的用途:

Operator Purpose 傳回類型
地圖 轉換每個資料項目(例如轉換溫度單位) DataModel
篩選 根據條件傳遞或丟棄物品 bool
分支 將物品路由到兩條不同的路徑 bool
累積 在時間窗內彙整項目 DataModel
Concatenate 合併多個資料流同時保持順序 不適用
延遲 提前時間戳以控制時間 不適用

模組是 WASM 的二進位,實作一個或多個運算元。 例如,單一 temperature.wasm 模組可以同時提供一個 map 運算子(用於轉換)和一個 filter 運算子(用於閾值檢查)。

Graph Definition → References Module → Provides Operator → Processes Data
     ↓                    ↓               ↓              ↓
"temperature:1.0.0" → temperature.wasm → map function → °F to °C

模組參照是相對於 registry 端點主機而言。 如果模組產物儲存在儲存庫路徑下,請將該路徑包含在模組參考中。 例如,對於登錄端點主機 ghcr.io,使用 azure-samples/explore-iot-operations/temperature:1.0.0 來參照 ghcr.io/azure-samples/explore-iot-operations/temperature:1.0.0。 使用扁平的私有登錄庫版面配置時,temperature:1.0.0 參考 <registry-host>/temperature:1.0.0。

這種分離讓你能重複使用不同的圖配置的同一模組,獨立使用版本模組,並透過設定參數改變行為而無需重建。

即時資料流模型

資料流程圖建立在Microsoft研究 Naiad 專案的 Timely dataflow 計算模型之上。 每個資料項目都帶有一個混合邏輯時鐘時間戳記:

record hybrid-logical-clock {
    timestamp: timespec,  // Wall-clock time (secs + nanos)
    counter: u64,         // Logical ordering for same-time events
    node-id: string,      // Originating node
}

這能帶來確定性處理(同一輸入總是產生相同輸出)、精確一次語意,以及跨節點的分散協調。 完整 WIT 架構請參見 samples repository。

欲了解如何使用 VS Code 擴充功能開發 WASM 模組,請參閱 「Build WASM modules with VS Code 擴充」。

撰寫運算符

映射運算子

映射運算子會轉換每個資料項目並回傳修改過的副本。 快速入門範例展示了一張基本地圖。 這裡有一個更複雜的範例,使用設定參數:

use std::sync::OnceLock;
use wasm_graph_sdk::logger::{self, Level};
use wasm_graph_sdk::macros::map_operator;

static OUTPUT_UNIT: OnceLock<String> = OnceLock::new();

fn unit_converter_init(configuration: ModuleConfiguration) -> bool {
    let unit = configuration.properties
        .iter()
        .find(|(k, _)| k == "output_unit")
        .map(|(_, v)| v.clone())
        .unwrap_or_else(|| "celsius".to_string());

    OUTPUT_UNIT.set(unit.clone()).unwrap();
    logger::log(Level::Info, "converter", &format!("Output unit: {unit}"));
    true
}

#[map_operator(init = "unit_converter_init")]
fn convert_temperature(input: DataModel) -> Result<DataModel, Error> {
    let DataModel::Message(mut msg) = input else {
        return Err(Error { message: "Expected Message variant".into() });
    };

    let payload = &msg.payload.read();
    let mut data: serde_json::Value = serde_json::from_slice(payload)
        .map_err(|e| Error { message: format!("JSON parse error: {e}") })?;

    if let Some(temp) = data["temperature"]["value"].as_f64() {
        let unit = OUTPUT_UNIT.get().map(|s| s.as_str()).unwrap_or("celsius");
        let converted = match unit {
            "kelvin" => (temp - 32.0) * 5.0 / 9.0 + 273.15,
            _ => (temp - 32.0) * 5.0 / 9.0, // celsius
        };
        data["temperature"]["value"] = serde_json::json!(converted);
        data["temperature"]["unit"] = serde_json::json!(unit);
        let out = serde_json::to_string(&data).unwrap();
        msg.payload = BufferOrBytes::Bytes(out.into_bytes());
    }

    Ok(DataModel::Message(msg))
}

篩選運算子

濾波器會回傳true以通過資料,或是回傳false以丟棄資料。

use std::sync::OnceLock;
use wasm_graph_sdk::macros::filter_operator;
use wasm_graph_sdk::logger::{self, Level};

const DEFAULT_LOWER: f64 = -40.0;
const DEFAULT_UPPER: f64 = 3422.0;

static LOWER_BOUND: OnceLock<f64> = OnceLock::new();
static UPPER_BOUND: OnceLock<f64> = OnceLock::new();

fn filter_init(configuration: ModuleConfiguration) -> bool {
    for (key, value) in &configuration.properties {
        match key.as_str() {
            "temperature_lower_bound" => {
                if let Ok(v) = value.parse::<f64>() { LOWER_BOUND.set(v).ok(); }
                else { logger::log(Level::Error, "filter", &format!("Invalid lower bound: {value}")); }
            }
            "temperature_upper_bound" => {
                if let Ok(v) = value.parse::<f64>() { UPPER_BOUND.set(v).ok(); }
                else { logger::log(Level::Error, "filter", &format!("Invalid upper bound: {value}")); }
            }
            _ => {}
        }
    }
    true
}

#[filter_operator(init = "filter_init")]
fn filter_temperature(input: DataModel) -> Result<bool, Error> {
    let lower = LOWER_BOUND.get().copied().unwrap_or(DEFAULT_LOWER);
    let upper = UPPER_BOUND.get().copied().unwrap_or(DEFAULT_UPPER);

    let DataModel::Message(msg) = &input else { return Ok(true); };
    let payload = &msg.payload.read();
    let data: serde_json::Value = serde_json::from_slice(payload)
        .map_err(|e| Error { message: format!("JSON parse error: {e}") })?;

    if let Some(temp) = data.get("temperature").and_then(|t| t.get("value")).and_then(|v| v.as_f64()) {
        Ok(temp >= lower && temp <= upper)
    } else {
        Ok(true) // Pass through non-temperature messages
    }
}

分支營運商

分支將資料路由到兩個路徑。 返回false用於第一個手臂,true用於第二個手臂。

use wasm_graph_sdk::macros::branch_operator;

fn branch_init(_configuration: ModuleConfiguration) -> bool { true }

#[branch_operator(init = "branch_init")]
fn branch_by_type(_timestamp: HybridLogicalClock, input: DataModel) -> Result<bool, Error> {
    let DataModel::Message(msg) = &input else { return Ok(true); };
    let payload = &msg.payload.read();
    let data: serde_json::Value = serde_json::from_slice(payload)
        .map_err(|e| Error { message: format!("JSON parse error: {e}") })?;

    // false = first arm (temperature data), true = second arm (everything else)
    Ok(data.get("temperature").is_none())
}

模組設定參數

你的運算元可以透過這個 init 函式接收執行時的設定參數。 這樣你就能自訂行為,而不必重建模組。

函式 init 接收一個 ModuleConfiguration 結構體:

record module-configuration {
    properties: list<tuple<string, string>>,   // Key-value pairs from graph definition
    module-schemas: list<module-schema>        // Schema definitions if configured
}

模組載入時,該 init 函式會被呼叫 一次 。 返回 true 以開始處理,或 false 表示設定錯誤。 如果 init 回傳 false,操作員將無法處理任何資料,資料流會記錄錯誤。

這很重要

如果你的操作員依賴設定參數(例如濾波器界限或閾值),那就一定要處理沒有提供這些參數的情況。 使用合理的預設值或從false返回init。 不要因為 unwrap() 缺少參數而呼叫或慌張,因為這會在執行時讓操作員當機,且沒有明顯錯誤訊息。

你在moduleConfigurations部分的圖定義中定義參數:

moduleConfigurations:
  - name: module-temperature/filter
    parameters:
      temperature_lower_bound:
        name: temperature_lower_bound
        description: "Minimum valid temperature in Celsius"
      temperature_upper_bound:
        name: temperature_upper_bound
        description: "Maximum valid temperature in Celsius"

欄位 name 必須與 operations 圖中運算子名稱相符。 欲了解更多圖定義結構,請參見 「配置 WebAssembly 圖定義」。

模組尺寸與效能

WASM 模組運行於資源有限的沙盒環境中。 請記住以下指引:

  • 盡量減少依賴。 對於 Rust,請使用 default-features = false 和 serdeserde_json 來減少二進位大小。 避免搬運大型箱子。
  • 模組大小很重要。 較小的模組載入更快,記憶體消耗較少。 典型的溫度轉換器為 ~2 MB(Rust 版本)或 ~5 MB(Python)。 使用發佈版本進行生產。
  • 避免阻塞操作。 這個 process 功能應該很快就會完成。 大量計算會延遲整個資料流程流程。
  • 用 wasm-tools 來檢查。 執行 wasm-tools component wit your-module.wasm 確認你的模組匯出預期介面,再推送到登錄檔。

版本控制與 CI/CD

對模組和圖定義使用語意版本控制。 資料流程圖會依路徑和標籤參考成品 (例如,針對扁平登錄配置使用 temperature:1.0.0,或針對巢狀存放庫配置使用 factory/graphs/temperature:1.0.0)。 你可以透過將新內容推送到同一個標籤,而不改變圖定義來更新模組。

對於自動化建置,典型的管線如下:

  1. 建置 WASM 模組(使用 Docker 建構器以保持一致性)。
  2. 執行 wasm-tools component wit 檢查匯出介面。
  3. 針對你的核心邏輯執行單元測試。 欲了解更多,請參閱 Test WASM 模組。
  4. 用 ORAS 推送到你的登錄檔,並標記建置版本。
  5. (可選) 更新圖形定義中的成品參考並推送。

資料流圖會自動接收推送到同一標籤的新模組版本,無需重新部署。 請參見 更新運行中圖表的模組。

主機 API

你的 WASM 模組可以使用主機 API 來管理狀態、記錄和指標。

狀態存放區

在通話間利用分散式狀態儲存庫來持久化資料:

use wasm_graph_sdk::state_store;

// Set value (fire-and-forget; state_store returns StateStoreError, not types::Error)
let options = state_store::SetOptions {
    conditions: state_store::SetConditions::Unconditional,
    expires: None,
};
let _ = state_store::set(key.as_bytes(), value.as_bytes(), None, None, options);

// Get value
let response = state_store::get(key.as_bytes(), None);

// Delete key
let _ = state_store::del(key.as_bytes(), None, None);

森林伐木業

結構化紀錄與嚴重程度等級:

use wasm_graph_sdk::logger::{self, Level};

logger::log(Level::Info, "my-operator", "Processing started");
logger::log(Level::Error, "my-operator", &format!("Error: {}", error));

Metrics

OpenTelemetry 相容計量:

use wasm_graph_sdk::metrics::{self, CounterValue, HistogramValue, Label};

let labels = vec![Label { key: "module".to_owned(), value: "my-operator".to_owned() }];
let _ = metrics::add_to_counter("requests_total", CounterValue::U64(1), Some(&labels));
let _ = metrics::record_to_histogram("processing_duration", HistogramValue::F64(duration_ms), Some(&labels));

ONNX 推論

若要在模組內嵌入和執行小型 ONNX 模型以進行頻內推斷,請參閱 在 WebAssembly 資料流程圖中執行 ONNX 推斷。

WIT 架構參考

所有運算子都會實作使用 WebAssembly 介面類型 (WIT) 定義的標準化介面。 你可以在 samples repository 找到完整的結構。

操作用戶介面

每個運算元都有 init 一個設定函數和一個 process 資料處理函數:

interface map {
    use types.{data-model, error, module-configuration};
    init: func(configuration: module-configuration) -> bool;
    process: func(message: data-model) -> result<data-model, error>;
}

interface filter {
    use types.{data-model, error, module-configuration};
    init: func(configuration: module-configuration) -> bool;
    process: func(message: data-model) -> result<bool, error>;
}

interface branch {
    use types.{data-model, error, module-configuration};
    use hybrid-logical-clock.{hybrid-logical-clock};
    init: func(configuration: module-configuration) -> bool;
    process: func(timestamp: hybrid-logical-clock, message: data-model) -> result<bool, error>;
}

interface accumulate {
    use types.{data-model, error, module-configuration};
    init: func(configuration: module-configuration) -> bool;
    process: func(staged: data-model, message: list<data-model>) -> result<data-model, error>;
}

資料模型

摘自 processor.wit (wasm-graph:processor@1.1.0):

record timestamp {
    timestamp: timespec,        // Physical time (seconds + nanoseconds)
    counter: u64,               // Logical counter for ordering
    node-id: buffer-or-string,  // Originating node
}

record message {
    timestamp: timestamp,
    topic: buffer-or-bytes,
    content-type: option<buffer-or-string>,
    payload: buffer-or-bytes,
    properties: message-properties,
    schema: option<message-schema>,
}

variant data-model {
    buffer-or-bytes(buffer-or-bytes),  // Raw byte data
    message(message),                  // MQTT messages (most common)
    snapshot(snapshot),                // Video/image frames
}

備註

大多數操作員會使用這個 message 變體。 在您的 process 函式開始時,檢查這種類型。 酬載會使用主機緩衝區句柄 (buffer) 來執行零複製讀取或模組擁有的位元組 (bytes)。 呼叫 buffer.read() 將主機位元組複製到模組記憶體。