在 Rust 中要求管道

必要條件

在本教學課程中,您將瞭解要求管道模式及其優點。本教學課程預期您已熟悉編寫及執行 FIDL 用戶端與伺服器的基本概念。詳情請參閱 Rust 入門教學課程

總覽

在 Fuchsia 上使用 FIDL 的一個常見層面是,將通訊協定本身透過通訊協定傳遞。許多 FIDL 訊息都包含用戶端端或管道的伺服器端,管道用來透過不同的 FIDL 通訊協定通訊。在這種情況下,用戶端代表管道的遠端端會實作指定的通訊協定,而伺服器端則代表遠端端是透過指定通訊協定發出要求。用戶端和伺服器端的一組替代條款是通訊協定和通訊協定要求。

本教學課程涵蓋:

  • FIDL 和 Rust FIDL 繫結中都會停止使用這些用戶端和伺服器。
  • 要求管道模式及其好處。

本教學課程的完整程式碼範例位於 //examples/fidl/rust/request_pipelining

FIDL 通訊協定

本教學課程實作 fuchsia.examples 程式庫中的 EchoLauncher 通訊協定:

@discoverable
closed protocol EchoLauncher {
    strict GetEcho(struct {
        echo_prefix string:MAX_STRING_LENGTH;
    }) -> (resource struct {
        response client_end:Echo;
    });
    strict GetEchoPipelined(resource struct {
        echo_prefix string:MAX_STRING_LENGTH;
        request server_end:Echo;
    });
};

這是一種通訊協定,可讓用戶端擷取 Echo 通訊協定的執行個體。用戶端可以指定前置字串,產生的 Echo 執行個體則會在每個回應中新增該前置字串。

你可以透過兩種方法達成這個目的:

  • GetEcho:使用前置字串做為要求,並透過該管道的用戶端端回應 (已連結至 Echo 通訊協定的實作頻道)。用戶端在回應中終止後,用戶端就可以透過用戶端,在 Echo 通訊協定上發出要求。
  • GetEchoPipelined:使用管道的前置字串和伺服器端做為要求,並將 Echo 的實作繫結至該要求。系統會假設發出要求的用戶端已保留用戶端端,並在呼叫 GetEchoPipeliend 後開始在該管道發出 Echo 要求。

顧名思義,後者使用名為通訊協定要求管道的模式,因此是建議採取的做法。本教學課程會實作這兩個方法。

實作伺服器

實作 Echo 通訊協定

這項 Echo 實作可讓您指定前置字串,以區分 Echo 伺服器的不同執行個體:

// An Echo implementation that adds a prefix to every response
async fn run_echo_server(stream: EchoRequestStream, prefix: &str) -> Result<(), Error> {
    stream
        .map(|result| result.context("failed request"))
        .try_for_each(|request| async move {
            match request {
                // The SendString request is not used in this example, so just
                // ignore it
                EchoRequest::SendString { value: _, control_handle: _ } => {}
                EchoRequest::EchoString { value, responder } => {
                    println!("Got echo request for prefix {}", prefix);
                    let response = format!("{}: {}", prefix, value);
                    responder.send(&response).context("error sending response")?;
                }
            }
            Ok(())
        })
        .await
}

由於用戶端僅使用 EchoString,因此 SendString 處理常式是空的。

實作 EchoLauncher 通訊協定

一般結構與 Echo 實作類似,差別在於使用 try_for_each_concurrent 而非 try_for_each。這個範例中的用戶端會啟動兩個 Echo 的執行個體,因此,使用並行版本可讓兩個對 run_echo_server 的呼叫並行執行:

// The EchoLauncher implementation that launches Echo servers with the specified
// prefix
async fn run_echo_launcher_server(stream: EchoLauncherRequestStream) -> Result<(), Error> {
    // Currently the client only connects at most two Echo clients for each EchoLauncher
    stream
        .map(|result| result.context("request error"))
        .try_for_each_concurrent(2, |request| async move {
            let (echo_prefix, server_end) = match request {
                // In the non pipelined case, we need to initialize the
                // communication channel ourselves
                EchoLauncherRequest::GetEcho { echo_prefix, responder } => {
                    println!("Got non pipelined request");
                    let (client_end, server_end) = create_endpoints::<EchoMarker>();
                    responder.send(client_end)?;
                    (echo_prefix, server_end)
                }
                // In the pipelined case, the client is responsible for
                // initializing the channel, and passes the server its end of
                // the channel
                EchoLauncherRequest::GetEchoPipelined {
                    echo_prefix,
                    request,
                    control_handle: _,
                } => {
                    println!("Got pipelined request");
                    (echo_prefix, request)
                }
            };
            // Run the Echo server with the specified prefix
            run_echo_server(server_end.into_stream()?, &echo_prefix).await
        })
        .await
}

系統會在管道的伺服器端呼叫 run_echo_server 來處理這兩個 EchoLauncher 方法。差別在於,在 GetEcho 中,伺服器會負責初始化管道,此時伺服器會使用其中一端做為伺服器,並將另一端傳回用戶端。在 GetEchoPipelined 中,要求會提供伺服器端點,因此伺服器不需要進行額外工作,因此不必回應。

// The EchoLauncher implementation that launches Echo servers with the specified
// prefix
async fn run_echo_launcher_server(stream: EchoLauncherRequestStream) -> Result<(), Error> {
    // Currently the client only connects at most two Echo clients for each EchoLauncher
    stream
        .map(|result| result.context("request error"))
        .try_for_each_concurrent(2, |request| async move {
            let (echo_prefix, server_end) = match request {
                // In the non pipelined case, we need to initialize the
                // communication channel ourselves
                EchoLauncherRequest::GetEcho { echo_prefix, responder } => {
                    println!("Got non pipelined request");
                    let (client_end, server_end) = create_endpoints::<EchoMarker>();
                    responder.send(client_end)?;
                    (echo_prefix, server_end)
                }
                // In the pipelined case, the client is responsible for
                // initializing the channel, and passes the server its end of
                // the channel
                EchoLauncherRequest::GetEchoPipelined {
                    echo_prefix,
                    request,
                    control_handle: _,
                } => {
                    println!("Got pipelined request");
                    (echo_prefix, request)
                }
            };
            // Run the Echo server with the specified prefix
            run_echo_server(server_end.into_stream()?, &echo_prefix).await
        })
        .await
}

提供 EchoLauncher 通訊協定

主要迴圈應與伺服器教學課程中的相同,但會提供 EchoLauncher,而非 Echo

enum IncomingService {
    EchoLauncher(EchoLauncherRequestStream),
}

#[fuchsia::main]
async fn main() -> Result<(), Error> {
    let mut fs = ServiceFs::new_local();
    fs.dir("svc").add_fidl_service(IncomingService::EchoLauncher);
    fs.take_and_serve_directory_handle()?;

    const MAX_CONCURRENT: usize = 1000;
    let fut = fs.for_each_concurrent(MAX_CONCURRENT, |IncomingService::EchoLauncher(stream)| {
        run_echo_launcher_server(stream).unwrap_or_else(|e| println!("{:?}", e))
    });

    println!("Running echo launcher server");
    fut.await;
    Ok(())
}

建構伺服器

或者,如要檢查設定是否正確,請嘗試建構伺服器:

  1. 設定 GN 版本以納入伺服器:

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

    fx build
    

實作用戶端

連線到 EchoLauncher 伺服器後,用戶端程式碼會使用 GetEchoGetEchoPipelined 連線至一個 Echo 執行個體,然後在每個執行個體上發出 EchoString 要求。

以下是非管道程式碼:

#[fuchsia::main]
async fn main() -> Result<(), Error> {
    let echo_launcher =
        connect_to_protocol::<EchoLauncherMarker>().context("Failed to connect to echo service")?;

    // Create a future that obtains an Echo protocol using the non-pipelined
    // GetEcho method
    let non_pipelined_fut = async {
        let client_end = echo_launcher.get_echo("not pipelined").await?;
        // "Upgrade" the client end in the response into an Echo proxy, and
        // make an EchoString request on it
        let proxy = client_end.into_proxy()?;
        proxy.echo_string("hello").map_ok(|val| println!("Got echo response {}", val)).await
    };

    // Create a future that obtains an Echo protocol using the pipelined GetEcho
    // method
    let (proxy, server_end) = create_proxy::<EchoMarker>()?;
    echo_launcher.get_echo_pipelined("pipelined", server_end)?;
    // We can make a request to the server right after sending the pipelined request
    let pipelined_fut =
        proxy.echo_string("hello").map_ok(|val| println!("Got echo response {}", val));

    // Run the two futures to completion
    let (non_pipelined_result, pipelined_result) = join!(non_pipelined_fut, pipelined_fut);
    pipelined_result?;
    non_pipelined_result?;
    Ok(())
}

此程式碼會鏈結兩個未來的版本。首先,它會向用戶端發出 GetEcho 要求。然後擷取結果,接著使用該結果建立用戶端物件 (proxy)、呼叫 EchoString,然後使用 await 封鎖結果。

雖然必須先初始化管道,但管道的程式碼會更加簡單:

#[fuchsia::main]
async fn main() -> Result<(), Error> {
    let echo_launcher =
        connect_to_protocol::<EchoLauncherMarker>().context("Failed to connect to echo service")?;

    // Create a future that obtains an Echo protocol using the non-pipelined
    // GetEcho method
    let non_pipelined_fut = async {
        let client_end = echo_launcher.get_echo("not pipelined").await?;
        // "Upgrade" the client end in the response into an Echo proxy, and
        // make an EchoString request on it
        let proxy = client_end.into_proxy()?;
        proxy.echo_string("hello").map_ok(|val| println!("Got echo response {}", val)).await
    };

    // Create a future that obtains an Echo protocol using the pipelined GetEcho
    // method
    let (proxy, server_end) = create_proxy::<EchoMarker>()?;
    echo_launcher.get_echo_pipelined("pipelined", server_end)?;
    // We can make a request to the server right after sending the pipelined request
    let pipelined_fut =
        proxy.echo_string("hello").map_ok(|val| println!("Got echo response {}", val));

    // Run the two futures to completion
    let (non_pipelined_result, pipelined_result) = join!(non_pipelined_fut, pipelined_fut);
    pipelined_result?;
    non_pipelined_result?;
    Ok(())
}

使用 create_proxy,這是建立管道兩端的捷徑,並將一端轉換為 Proxy。呼叫 GetEchoPipelined 後,用戶端可以立即發出 EchoString 要求。

最後,與非管道和管道呼叫相對應的兩個未來會並行執行,以查看哪一個較先完成:

#[fuchsia::main]
async fn main() -> Result<(), Error> {
    let echo_launcher =
        connect_to_protocol::<EchoLauncherMarker>().context("Failed to connect to echo service")?;

    // Create a future that obtains an Echo protocol using the non-pipelined
    // GetEcho method
    let non_pipelined_fut = async {
        let client_end = echo_launcher.get_echo("not pipelined").await?;
        // "Upgrade" the client end in the response into an Echo proxy, and
        // make an EchoString request on it
        let proxy = client_end.into_proxy()?;
        proxy.echo_string("hello").map_ok(|val| println!("Got echo response {}", val)).await
    };

    // Create a future that obtains an Echo protocol using the pipelined GetEcho
    // method
    let (proxy, server_end) = create_proxy::<EchoMarker>()?;
    echo_launcher.get_echo_pipelined("pipelined", server_end)?;
    // We can make a request to the server right after sending the pipelined request
    let pipelined_fut =
        proxy.echo_string("hello").map_ok(|val| println!("Got echo response {}", val));

    // Run the two futures to completion
    let (non_pipelined_result, pipelined_result) = join!(non_pipelined_fut, pipelined_fut);
    pipelined_result?;
    non_pipelined_result?;
    Ok(())
}

建構用戶端

(選用) 如要檢查內容是否正確,請嘗試建立用戶端:

  1. 設定 GN 版本以納入伺服器:

    fx set core.x64 --with //examples/fidl/rust/request_pipelining/client:echo-client
    
  2. 建構 Fuchsia 映像檔:

    fx build
    

執行範例程式碼

fuchsia.examples.Echofuchsia.examples.EchoLauncher

  1. 設定您的版本以納入包含 echo 領域、伺服器和用戶端的套件:

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

    fx build
    
  3. 執行 echo_realm 元件。這會建立用戶端和伺服器元件執行個體,並轉送功能:

    ffx component run /core/ffx-laboratory:echo_realm fuchsia-pkg://fuchsia.com/echo-launcher-rust#meta/echo_realm.cm
    
  4. 啟動 echo_client 執行個體:

    ffx component start /core/ffx-laboratory:echo_realm/echo_client
    

在用戶端嘗試連線至 EchoLauncher 通訊協定時,伺服器元件會啟動。您應該會在裝置記錄 (ffx log) 中看到類似以下的輸出內容:

[echo_server][][I] Running echo launcher server
[echo_server][][I] Got pipelined request
[echo_server][][I] Got echo request for prefix pipelined
[echo_server][][I] Got non pipelined request
[echo_client][][I] Got echo response pipelined: hello
[echo_server][][I] Got echo request for prefix not pipelined
[echo_client][][I] Got echo response not pipelined: hello

依據列印順序,可看出管道流向較快。即使系統先傳送非管道要求,但會優先到達管道案例的 echo 回應,因為要求管道會儲存用戶端與伺服器之間的往返作業。要求管道也可以簡化程式碼。

如要進一步瞭解通訊協定要求管道,包括如何處理可能失敗的通訊協定要求,請參閱 FIDL API 評分量表

終止領域元件以停止執行並清除元件執行個體:

ffx component destroy /core/ffx-laboratory:echo_realm