在 Rust 中實作 FIDL 伺服器

必要條件

本教學課程假設您已熟悉如何將程式庫的 FIDL Rust 繫結列為 GN 中的依附元件,以及如何將繫結匯入 Rust 程式碼 (這部分內容已在 Rust FIDL Crate 教學課程中說明)。

總覽

本教學課程說明如何實作 FIDL 通訊協定 (fuchsia.examples.Echo) 並在 Fuchsia 上執行。這個通訊協定有各種類型的方法:

  • EchoString 是有回應的方法。
  • SendString 是沒有回應的方法。
  • OnString 是事件。
@discoverable
closed protocol Echo {
    strict EchoString(struct {
        value string:MAX_STRING_LENGTH;
    }) -> (struct {
        response string:MAX_STRING_LENGTH;
    });
    strict SendString(struct {
        value string:MAX_STRING_LENGTH;
    });
    strict -> OnString(struct {
        response string:MAX_STRING_LENGTH;
    });
};

如要進一步瞭解 FIDL 方法和訊息傳遞模型,請參閱 FIDL 概念頁面。

本文說明如何完成下列工作:

  • 實作 FIDL 通訊協定。
  • 在 Fuchsia 上建構並執行套件。
  • 提供 FIDL 通訊協定。

本教學課程首先會建立元件,並提供給 Fuchsia 裝置執行。然後逐步新增功能,讓伺服器開始運作。

如要自行編寫程式碼,請刪除下列目錄:

rm -r examples/fidl/rust/server/*

建立元件

如要建立元件,請按照下列步驟操作:

  1. examples/fidl/rust/server/src/main.rs 中新增 main() 函式:

    fn main() {
      println!("Hello, world!");
    }
    
  2. examples/fidl/rust/server/BUILD.gn 中宣告伺服器的目標:

    import("//build/rust/rustc_binary.gni")
    
    
    # Declare an executable for the server. This produces a binary with the
    # specified output name that can run on Fuchsia.
    rustc_binary("bin") {
      output_name = "fidl_echo_rust_server"
      edition = "2024"
    
      sources = [ "src/main.rs" ]
    }
    
    # Declare a component for the server, which consists of the manifest and the
    # binary that the component will run.
    fuchsia_component("echo-server") {
      component_name = "echo_server"
      manifest = "meta/server.cml"
      deps = [ ":bin" ]
    }
    
    # Declare a package that contains a single component, our server.
    fuchsia_package("echo-rust-server") {
      deps = [ ":echo-server" ]
    }
    

    如要啟動並執行伺服器元件,需要定義下列三個目標:

    • 伺服器的原始可執行檔,建構後可在 Fuchsia 上執行。
    • 這個元件設定為只執行伺服器可執行檔,並使用元件的資訊清單檔案說明。
    • 然後將元件放入套件,這是 Fuchsia 上的軟體發布單位。在本例中,套件只包含單一元件。

    如要進一步瞭解套件、元件和建構方式,請參閱「建構元件」頁面。

  3. examples/fidl/rust/server/meta/server.cml 中新增元件資訊清單:

    {
        include: [ "syslog/client.shard.cml" ],
    
        // Information about the program to run.
        program: {
            // Use the built-in ELF runner.
            runner: "elf",
    
            // The binary to run for this component.
            binary: "bin/fidl_echo_rust_server",
        },
    
        // Capabilities provided by this component.
        capabilities: [
            { protocol: "fuchsia.examples.Echo" },
        ],
        expose: [
            {
                protocol: "fuchsia.examples.Echo",
                from: "self",
            },
        ],
    }
    
    
  4. 將伺服器新增至建構設定:

    fx set core.x64 --with //examples/fidl/rust/server:echo-rust-server
  5. 建構 Fuchsia 映像檔:

    fx build

導入伺服器

首先,您要實作 Echo 通訊協定的行為。在 Rust 中,這會以可處理通訊協定相關聯要求串流型別的程式碼表示,在本例中為 EchoRequestStream。這種類型是 Echo 要求的串流,也就是實作 futures::Stream<Item = Result<EchoRequest, fidl::Error>>

您將實作 run_echo_server() 來處理要求串流,這是處理傳入服務要求的非同步函式。並傳回在用戶端管道關閉後完成的 Future。

新增依附元件

  1. 匯入必要依附元件:

    // we'll use anyhow to propagate errors that occur when handling the request stream
    use anyhow::{Context as _, Error};
    // the server will need to handle an EchoRequestStream
    use fidl_fuchsia_examples::{EchoRequest, EchoRequestStream};
    // import the futures prelude, which includes things like the Future and Stream traits
    use futures::prelude::*;
    
  2. 將這些項目新增為 rustc_binary 目標的建構依附元件。deps 欄位應如下所示:

    deps = [
      "//examples/fidl/fuchsia.examples:fuchsia.examples_rust",
      "//third_party/rust_crates:anyhow",
      "//third_party/rust_crates:futures",
    ]
    

定義「run_echo_server」:

// An implementation of the Echo stream, which handles a stream of EchoRequests
async fn run_echo_server(stream: EchoRequestStream) -> Result<(), Error> {
    stream
        .map(|result| result.context("failed request"))
        .try_for_each(|request| async move {
            match request {
                // Handle each EchoString request by responding with the request
                // value
                EchoRequest::EchoString { value, responder } => {
                    println!("Received EchoString request for string {:?}", value);
                    responder.send(&value).context("error sending response")?;
                    println!("Response sent successfully");
                }
                // Handle each SendString request by sending a single OnString
                // event with the request value
                EchoRequest::SendString { value, control_handle } => {
                    println!("Received SendString request for string {:?}", value);
                    control_handle.send_on_string(&value).context("error sending event")?;
                    println!("Event sent successfully");
                }
            }
            Ok(())
        })
        .await
}

實作作業包含下列元素:

  • 程式碼會將要求串流中的 fidl:Error 轉換為 anyhow::Error,方法是在每個結果上使用 .context() 方法附加內容:

    // An implementation of the Echo stream, which handles a stream of EchoRequests
    async fn run_echo_server(stream: EchoRequestStream) -> Result<(), Error> {
        stream
            .map(|result| result.context("failed request"))
            .try_for_each(|request| async move {
                match request {
                    // Handle each EchoString request by responding with the request
                    // value
                    EchoRequest::EchoString { value, responder } => {
                        println!("Received EchoString request for string {:?}", value);
                        responder.send(&value).context("error sending response")?;
                        println!("Response sent successfully");
                    }
                    // Handle each SendString request by sending a single OnString
                    // event with the request value
                    EchoRequest::SendString { value, control_handle } => {
                        println!("Received SendString request for string {:?}", value);
                        control_handle.send_on_string(&value).context("error sending event")?;
                        println!("Event sent successfully");
                    }
                }
                Ok(())
            })
            .await
    }
    

    在這個階段,Result<EchoRequest, fidl::Error> 串流會變成 Result<EchoRequest, anyhow::Error> 串流。

  • 接著,函式會對產生的串流呼叫 try_for_each,並傳回未來。這個方法會將串流中的 Result 解除包裝,任何失敗都會導致該 Future 立即傳回錯誤,而任何成功內容都會傳遞至閉包。同樣地,如果閉包的傳回值解析為失敗,產生的 Future 會立即傳回該錯誤:

    // An implementation of the Echo stream, which handles a stream of EchoRequests
    async fn run_echo_server(stream: EchoRequestStream) -> Result<(), Error> {
        stream
            .map(|result| result.context("failed request"))
            .try_for_each(|request| async move {
                match request {
                    // Handle each EchoString request by responding with the request
                    // value
                    EchoRequest::EchoString { value, responder } => {
                        println!("Received EchoString request for string {:?}", value);
                        responder.send(&value).context("error sending response")?;
                        println!("Response sent successfully");
                    }
                    // Handle each SendString request by sending a single OnString
                    // event with the request value
                    EchoRequest::SendString { value, control_handle } => {
                        println!("Received SendString request for string {:?}", value);
                        control_handle.send_on_string(&value).context("error sending event")?;
                        println!("Event sent successfully");
                    }
                }
                Ok(())
            })
            .await
    }
    
  • 封閉包裝的內容會比對傳入的 EchoRequest,判斷要求類型:

    // An implementation of the Echo stream, which handles a stream of EchoRequests
    async fn run_echo_server(stream: EchoRequestStream) -> Result<(), Error> {
        stream
            .map(|result| result.context("failed request"))
            .try_for_each(|request| async move {
                match request {
                    // Handle each EchoString request by responding with the request
                    // value
                    EchoRequest::EchoString { value, responder } => {
                        println!("Received EchoString request for string {:?}", value);
                        responder.send(&value).context("error sending response")?;
                        println!("Response sent successfully");
                    }
                    // Handle each SendString request by sending a single OnString
                    // event with the request value
                    EchoRequest::SendString { value, control_handle } => {
                        println!("Received SendString request for string {:?}", value);
                        control_handle.send_on_string(&value).context("error sending event")?;
                        println!("Event sent successfully");
                    }
                }
                Ok(())
            })
            .await
    }
    

    這項實作會處理 EchoString 要求 (將輸入內容回傳),並傳送 OnString 事件來處理 SendString 要求。由於 SendString 是「即發即忘」方法,因此要求列舉變數會隨附控制代碼,可用於與伺服器通訊。

    在這兩種情況下,系統都會透過新增內容並使用 ? 運算子,傳播將訊息傳回給用戶端的錯誤。如果順利到達結尾,則會傳回 Ok(())

  • 最後,伺服器函式 await 會將 try_for_each 傳回的 Future 設為完成,這會在每個傳入要求上呼叫閉包,並在處理完所有要求或發生任何錯誤時傳回。

您可以執行下列指令,確認導入作業是否正確:

fx build

提供通訊協定

您已定義處理傳入要求的程式碼,現在需要監聽傳入的連線,連線至 Echo 伺服器。方法是要求元件管理員向其他元件公開 Echo 通訊協定。元件管理員接著會將所有回音通訊協定要求轉送至我們的伺服器。

為滿足這些要求,元件管理員需要通訊協定的名稱,以及在有任何連線至符合指定名稱通訊協定的連入要求時,應呼叫的處理常式。

新增依附元件

  1. 匯入必要依附元件:

    // Import the Fuchsia async runtime in order to run the async main function
    use fuchsia_async as fasync;
    // ServiceFs is a filesystem used to connect clients to the Echo service
    use fuchsia_component::server::ServiceFs;
    
  2. 將這些項目新增為 rustc_binary 目標的建構依附元件。完整目標如下所示:

    rustc_binary("bin") {
      name = "fidl_echo_rust_server"
      edition = "2024"
    
      deps = [
        "//examples/fidl/fuchsia.examples:fuchsia.examples_rust",
        "//src/lib/fuchsia",
        "//src/lib/fuchsia-component",
        "//third_party/rust_crates:anyhow",
        "//third_party/rust_crates:futures",
      ]
    
      sources = [ "src/main.rs" ]
    }
    
    

定義 main 函式

#[fuchsia::main]
async fn main() -> Result<(), Error> {
    // Initialize the outgoing services provided by this component
    let mut fs = ServiceFs::new_local();
    fs.dir("svc").add_fidl_service(IncomingService::Echo);

    // Serve the outgoing services
    fs.take_and_serve_directory_handle()?;

    // Listen for incoming requests to connect to Echo, and call run_echo_server
    // on each one
    println!("Listening for incoming connections...");
    const MAX_CONCURRENT: usize = 10_000;
    fs.for_each_concurrent(MAX_CONCURRENT, |IncomingService::Echo(stream)| {
        run_echo_server(stream).unwrap_or_else(|e| println!("{:?}", e))
    })
    .await;

    Ok(())
}

主函式是非同步函式,因為它會監聽傳入 Echo 伺服器的連線。fuchsia::main 屬性會告知 Fuchsia 非同步執行階段,在單一執行緒上執行 main future 直到完成。

main 也會傳回 Result<(), Error>。如果 main 因其中一行 ? 而傳回 Error,系統會列印 Debug 錯誤,並傳回表示失敗的狀態碼。

初始化 ServiceFs

取得 ServiceFs 的執行個體,代表包含各種服務的檔案系統。由於伺服器會以單一執行緒執行,請使用 ServiceFs::new_local(),而非 ServiceFs::new() (後者可處理多個執行緒)。

#[fuchsia::main]
async fn main() -> Result<(), Error> {
    // Initialize the outgoing services provided by this component
    let mut fs = ServiceFs::new_local();
    fs.dir("svc").add_fidl_service(IncomingService::Echo);

    // Serve the outgoing services
    fs.take_and_serve_directory_handle()?;

    // Listen for incoming requests to connect to Echo, and call run_echo_server
    // on each one
    println!("Listening for incoming connections...");
    const MAX_CONCURRENT: usize = 10_000;
    fs.for_each_concurrent(MAX_CONCURRENT, |IncomingService::Echo(stream)| {
        run_echo_server(stream).unwrap_or_else(|e| println!("{:?}", e))
    })
    .await;

    Ok(())
}

新增 Echo FIDL 服務

請元件管理員公開 Echo FIDL 服務。這項函式呼叫包含兩個部分:

#[fuchsia::main]
async fn main() -> Result<(), Error> {
    // Initialize the outgoing services provided by this component
    let mut fs = ServiceFs::new_local();
    fs.dir("svc").add_fidl_service(IncomingService::Echo);

    // Serve the outgoing services
    fs.take_and_serve_directory_handle()?;

    // Listen for incoming requests to connect to Echo, and call run_echo_server
    // on each one
    println!("Listening for incoming connections...");
    const MAX_CONCURRENT: usize = 10_000;
    fs.for_each_concurrent(MAX_CONCURRENT, |IncomingService::Echo(stream)| {
        run_echo_server(stream).unwrap_or_else(|e| println!("{:?}", e))
    })
    .await;

    Ok(())
}
  • 元件管理員必須知道如何處理連線要求。方法是傳入接受 fidl::endpoints::RequestStream 的閉包,並傳回一些新值。舉例來說,傳入 |stream: EchoRequestStream| stream 的閉包完全有效。常見模式是定義伺服器提供的可能服務列舉,在本範例中為:

    enum IncomingService {
        // Host a service protocol.
        Echo(EchoRequestStream),
        // ... more services here
    }
    

    然後將列舉變數「建構函式」做為閉包傳遞。如果提供多項服務,這會產生常見的傳回型別 (IncomingService 列舉)。監聽連入連線時,所有 add_fidl_service 閉包的回傳值都會成為 ServiceFs 串流中的元素。

  • 元件管理員也必須知道這項服務的適用範圍。 由於這是輸出服務 (即提供給其他元件的服務),因此服務必須在 /svc 目錄中新增路徑。add_fidl_service 會透過與閉包輸入引數相關聯的 SERVICE_NAME,隱含取得這個路徑。在本例中,閉包引數 (IncomingService::Echo) 具有 EchoRequestStream 類型的輸入引數,而該引數具有 "fuchsia.examples.Echo" 的相關聯 SERVICE_NAME。因此,這項呼叫會在 /svc/fuchsia.examples.Echo 新增項目,用戶端必須搜尋名為 "fuchsia.examples.Echo" 的服務,才能連線至這個伺服器。

提供傳出目錄

#[fuchsia::main]
async fn main() -> Result<(), Error> {
    // Initialize the outgoing services provided by this component
    let mut fs = ServiceFs::new_local();
    fs.dir("svc").add_fidl_service(IncomingService::Echo);

    // Serve the outgoing services
    fs.take_and_serve_directory_handle()?;

    // Listen for incoming requests to connect to Echo, and call run_echo_server
    // on each one
    println!("Listening for incoming connections...");
    const MAX_CONCURRENT: usize = 10_000;
    fs.for_each_concurrent(MAX_CONCURRENT, |IncomingService::Echo(stream)| {
        run_echo_server(stream).unwrap_or_else(|e| println!("{:?}", e))
    })
    .await;

    Ok(())
}

這項呼叫會將 ServiceFs 繫結至元件的 DirectoryRequest 啟動控制代碼,並監聽連入的連線要求。請注意,由於這會從程序的控制代碼表格中移除控制代碼,因此每個程序只能呼叫這個函式一次。如要將 ServiceFs 提供給其他管道,可以使用 serve_connection 函式。

如要進一步瞭解這項程序,請參閱「通訊協定開啟的生命週期」。

接聽連入連線

執行 ServiceFs 直到完成,即可監聽連入連線:

#[fuchsia::main]
async fn main() -> Result<(), Error> {
    // Initialize the outgoing services provided by this component
    let mut fs = ServiceFs::new_local();
    fs.dir("svc").add_fidl_service(IncomingService::Echo);

    // Serve the outgoing services
    fs.take_and_serve_directory_handle()?;

    // Listen for incoming requests to connect to Echo, and call run_echo_server
    // on each one
    println!("Listening for incoming connections...");
    const MAX_CONCURRENT: usize = 10_000;
    fs.for_each_concurrent(MAX_CONCURRENT, |IncomingService::Echo(stream)| {
        run_echo_server(stream).unwrap_or_else(|e| println!("{:?}", e))
    })
    .await;

    Ok(())
}

這會執行 ServiceFs Future,同時處理最多 10,000 個傳入要求。傳遞至這項呼叫的閉包是處理傳入要求的處理常式 - ServiceFs 會先將傳入連線與提供給 add_fidl_service 的閉包相符,然後在結果 (即 IncomingService) 上呼叫處理常式。處理常式會採用 IncomingService,並在內部要求串流上呼叫 run_echo_server,以處理傳入的 Echo 要求。

這裡會處理兩種要求。ServiceFs 處理的要求串流包含連線至 Echo 伺服器的要求 (也就是說,每個用戶端在連線至伺服器時,都會發出這類要求一次),而 run_echo_server 處理的要求串流則是 Echo 通訊協定上的要求 (也就是說,每個用戶端可能會對伺服器發出任意數量的 EchoStringSendString 要求)。許多用戶端可以同時要求連線至 Echo 伺服器,因此系統會並行處理這類要求。不過,單一用戶端的所有要求都會依序發生,因此並行處理要求沒有好處。

測試伺服器

重建:

fx build

然後執行伺服器元件:

ffx component run /core/ffx-laboratory:echo_server fuchsia-pkg://fuchsia.com/echo-rust-server#meta/echo_server.cm

注意:元件會使用元件網址 (由`fuchsia-pkg://`配置決定) 進行解析。

裝置記錄 (ffx log) 應會顯示類似以下的輸出內容:

[ffx-laboratory:echo_server][][I] Listening for incoming connections...

伺服器現已開始執行並等待傳入要求。下一步是編寫傳送 Echo 通訊協定要求的用戶端。目前,您只要終止伺服器元件即可:

ffx component destroy /core/ffx-laboratory:echo_server