連結元件

通訊協定控制代碼為知名物件,提供實作 FIDL 通訊協定,可透過元件命名空間探索。 功能轉送描述應做為任何特定用戶端的供應器。

請參考下列 fuchsia.example.Foo 通訊協定的範例:

這張圖表顯示連結元件如何結合能力轉送和通訊協定提供。元件必須支援其他元件提供的通訊協定實作。

下圖醒目顯示執行連線的主要元素:

  1. 供應商元件會以靜態方式宣告資訊清單 capabilities 區段中的通訊協定。這讓元件架構可以執行能力轉送。
  2. 用戶端元件會以靜態方式要求資訊清單 use 區段中的通訊協定。如果能力轉送成功,這會在用戶端的命名空間中建立 /svc/fuchsia.example.Foo 通訊協定項目。
  3. 供應商程式碼會在執行階段發布實作項目。這會在供應器的傳出目錄的 /svc/fuchsia.example.Foo 建立通訊協定項目。
  4. 用戶端程式碼會在執行階段與通訊協定控制代碼連線。這個動作會開啟 FIDL 連線,連結至在供應器元件中執行的實作。

發布通訊協定實作

實作 FIDL 通訊協定的元件會在其元件資訊清單中宣告公開該通訊協定為能力。這可讓元件架構執行能力轉送,從這個元件到要求該能力的拓撲中的其他項目。

{
    // ...
    capabilities: [
        { protocol: "fuchsia.example.Foo" },
    ],
    expose: [
        {
            protocol: "fuchsia.example.Foo",
            from: "self",
        },
    ],
}

功能轉送會說明通訊協定的存取權限,但不會建立連線所需的端點。元件必須使用 fuchsia.io 通訊協定,將實作內容以 /svc/ 控制代碼發布至傳出目錄。產生的 FIDL 繫結會包裝此控點,並讓提供者連結要求控制代碼,以開始接收 FIDL 訊息。

Rust

let mut service_fs = ServiceFs::new_local();

// Serve the protocol
service_fs.dir("svc").add_fidl_service(PROTOCOL_NAME);
service_fs.take_and_serve_directory_handle().context("failed to serve outgoing namespace")?;

C++

// Serve the protocol
FooImplementation instance;
fidl::Binding<fuchsia::example::Foo> binding(&instance);
instance.event_sender_ = &binding.events();
fidl::InterfaceRequestHandler<fuchsia::example::Foo> handler =
    [&](fidl::InterfaceRequest<fuchsia::example::Foo> request) {
      binding.Bind(std::move(request));
    };
context->outgoing()->AddPublicService(std::move(handler));

連線至通訊協定實作

用戶端元件會在其元件資訊清單中,將通訊協定宣告為必要能力。這可讓元件架構判斷元件是否有權存取通訊協定實作。如果路徑存在,元件的命名空間就會包含對應的 /svc/ 控制代碼。

{
    // ...
    use: [
        { protocol: "fuchsia.example.Foo" },
    ],
}

用戶端元件使用 fuchsia.io 通訊協定與通訊協定實作建立連線,並開啟管道。產生的 FIDL 繫結會包裝這個管道,並讓用戶端開始傳送訊息至供應器。

Rust

// Connect to FIDL protocol
let protocol = connect_to_protocol::<FooMarker>().expect("error connecting to echo");

C++

// Connect to FIDL protocol
fuchsia::example::FooSyncPtr proxy;
auto context = sys::ComponentContext::Create();
context->svc()->Connect(proxy.NewRequest());

練習:Echo 伺服器和用戶端

在本節中,您將使用針對 fidl.examples.routing.echo 產生的 FIDL 繫結,在 Rust 中實作用戶端和伺服器元件。

啟動模擬器

如果您尚未有一個執行中的執行個體,請啟動模擬器:

  1. 啟動新的模擬器執行個體:

    ffx emu start --headless
    

    啟動完成後,模擬器會輸出下列訊息並傳回:

    Logging to "$HOME/.local/share/Fuchsia/ffx/emu/instances/fuchsia-emulator/emulator.log"
    Waiting for Fuchsia to start (up to 60 seconds)........
    Emulator is ready.
    
  2. 啟動套件伺服器,讓模擬器載入軟體套件:

    fx serve
    

建立伺服器元件

請先建立新的元件專案來實作 echo 伺服器。這個元件將提供 Echo 通訊協定並處理傳入要求。

//vendor/fuchsia-codelab 目錄中為名為 echo-server 的新元件建立專案鷹架:

mkdir -p vendor/fuchsia-codelab/echo-server

在新專案目錄中建立以下檔案和目錄結構:

Rust

//vendor/fuchsia-codelab/echo-server
                        |- BUILD.gn
                        |- meta
                        |   |- echo.cml
                        |
                        |- src
                            |- main.rs

C++

//vendor/fuchsia-codelab/echo-server
                        |- BUILD.gn
                        |- meta
                        |   |- echo.cml
                        |
                        |- main.cc

將以下建構規則新增至 BUILD.gn 檔案,以便建構及套件伺服器元件:

Rust

echo-server/BUILD.gn:

import("//build/components.gni")
import("//build/rust/rustc_binary.gni")


rustc_binary("bin") {
  output_name = "echo-server"
  edition = "2021"

  deps = [
    "//vendor/fuchsia-codelab/echo-fidl:echo_rust",
    "//src/lib/diagnostics/inspect/runtime/rust",
    "//src/lib/diagnostics/inspect/rust",
    "//src/lib/fuchsia",
    "//src/lib/fuchsia-component",
    "//third_party/rust_crates:anyhow",
    "//third_party/rust_crates:futures",
  ]

  sources = [ "src/main.rs" ]
}

# Unpackaged component "#meta/echo_server.cm"
fuchsia_component("echo_server_cmp") {
  component_name = "echo_server"
  manifest = "meta/echo_server.cml"
  deps = [ ":bin" ]
}

fuchsia_package("echo-server") {
  package_name = "echo-server"
  deps = [ ":component" ]
}

C++

echo-server/BUILD.gn:

import("//build/components.gni")


executable("bin") {
  output_name = "echo-server"
  sources = [ "main.cc" ]

  deps = [
    "//vendor/fuchsia-codelab/echo-fidl:echo_hlcpp",
    "//sdk/lib/inspect/component/cpp",
    "//sdk/lib/sys/cpp",
    "//zircon/system/ulib/async-loop:async-loop-cpp",
    "//zircon/system/ulib/async-loop:async-loop-default",
  ]
}

# Unpackaged component "#meta/echo_server.cm"
fuchsia_component("echo_server_cmp") {
  component_name = "echo_server"
  manifest = "meta/echo_server.cml"
  deps = [ ":bin" ]
}

fuchsia_package("echo-server") {
  package_name = "echo-server"
  deps = [ ":component" ]
}

Echo 通訊協定宣告為伺服器元件提供的能力,並公開該通訊協定供父項運作領域使用:

Rust

echo-server/meta/echo_server.cml:

{
    include: [
        "inspect/client.shard.cml",
        "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/echo-server",
    },

    // Capabilities provided by this component.
    capabilities: [
        { protocol: "fidl.examples.routing.echo.Echo" },
    ],
    expose: [
        {
            protocol: "fidl.examples.routing.echo.Echo",
            from: "self",
        },
    ],
}

C++

echo-server/meta/echo_server.cml:

{
    include: [
        "inspect/client.shard.cml",
        "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/echo-server",
    },

    // Capabilities provided by this component.
    capabilities: [
        { protocol: "fidl.examples.routing.echo.Echo" },
    ],
    expose: [
        {
            protocol: "fidl.examples.routing.echo.Echo",
            from: "self",
        },
    ],
}

實作伺服器

開啟主要來源檔案,並將匯入陳述式替換為下列程式碼:

Rust

echo-server/src/main.rs:

use anyhow::Context;
use fidl_fidl_examples_routing_echo::{EchoRequest, EchoRequestStream};
use fuchsia_component::server::ServiceFs;
use fuchsia_inspect::{component, health::Reporter};
use futures::prelude::*;

C++

echo-server/main.cc:

#include <fidl/examples/routing/echo/cpp/fidl.h>
#include <lib/async-loop/cpp/loop.h>
#include <lib/async-loop/default.h>
#include <lib/fidl/cpp/binding.h>
#include <lib/inspect/component/cpp/component.h>
#include <lib/sys/cpp/component_context.h>

將下列程式碼新增至 main(),以提供 Echo 通訊協定:

Rust

echo-server/src/main.rs:

// Wrap protocol requests being served.
enum IncomingRequest {
    Echo(EchoRequestStream),
}

#[fuchsia::main(logging = false)]
async fn main() -> Result<(), anyhow::Error> {
    let mut service_fs = ServiceFs::new_local();

    // Initialize inspect
    component::health().set_starting_up();
    let _inspect_server_task = inspect_runtime::publish(
        component::inspector(),
        inspect_runtime::PublishOptions::default(),
    );

    // Serve the Echo protocol
    service_fs.dir("svc").add_fidl_service(IncomingRequest::Echo);
    service_fs.take_and_serve_directory_handle().context("failed to serve outgoing namespace")?;

    // Component is serving and ready to handle incoming requests
    component::health().set_ok();

    // Attach request handler for incoming requests
    service_fs
        .for_each_concurrent(None, |request: IncomingRequest| async move {
            match request {
                IncomingRequest::Echo(stream) => handle_echo_request(stream).await,
            }
        })
        .await;

    Ok(())
}

這個程式碼會執行下列步驟來提供 Echo 通訊協定:

  1. 初始化 ServiceFs,然後在傳出目錄的 /svc/fidl.examples.routing.echo.Echo 底下新增項目。
  2. 提供目錄,然後開始監聽連入連線。
  3. 針對任何相符的 Echo 要求,將 handle_echo_request() 函式新增為要求處理常式。

C++

echo-server/main.cc:

int main(int argc, const char** argv) {
  async::Loop loop(&kAsyncLoopConfigAttachToCurrentThread);
  auto context = sys::ComponentContext::CreateAndServeOutgoingDirectory();

  // Initialize inspect
  inspect::ComponentInspector inspector(loop.dispatcher(), inspect::PublishOptions{});
  inspector.Health().StartingUp();

  // Serve the Echo protocol
  EchoImplementation echo_instance;
  fidl::Binding<fidl::examples::routing::echo::Echo> binding(&echo_instance);
  echo_instance.event_sender_ = &binding.events();
  fidl::InterfaceRequestHandler<fidl::examples::routing::echo::Echo> handler =
      [&](fidl::InterfaceRequest<fidl::examples::routing::echo::Echo> request) {
        binding.Bind(std::move(request));
      };
  context->outgoing()->AddPublicService(std::move(handler));

  // Component is serving and ready to handle incoming requests
  inspector.Health().Ok();

  return loop.Run();
}

這個程式碼會執行下列步驟來提供 Echo 通訊協定:

  1. 初始化 ComponentContext,然後在傳出目錄的 /svc/fidl.examples.routing.echo.Echo 底下新增項目。
  2. 提供目錄,然後開始監聽連入連線。
  3. 針對任何相符的 Echo 要求,將 EchoImplementation 執行個體做為要求處理常式進行附加。

新增以下程式碼,實作通訊協定要求處理常式:

Rust

echo-server/src/main.rs:

// Handler for incoming service requests
async fn handle_echo_request(mut stream: EchoRequestStream) {
    while let Some(event) = stream.try_next().await.expect("failed to serve echo service") {
        let EchoRequest::EchoString { value, responder } = event;
        responder.send(value.as_ref().map(|s| &**s)).expect("failed to send echo response");
    }
}

EchoRequestStream 中的每個要求都會以方法名稱 (EchoString) 輸入,並附上回應器介面來傳回傳回值。

C++

echo-server/main.cc:

// Handler for incoming service requests
class EchoImplementation : public fidl::examples::routing::echo::Echo {
 public:
  void EchoString(fidl::StringPtr value, EchoStringCallback callback) override { callback(value); }
  fidl::examples::routing::echo::Echo_EventSender* event_sender_;
};

每個 Echo 通訊協定方法都有對應的覆寫函式 (EchoString()),並提供可傳回傳回值的回呼介面。

這種實作方式會直接「echo」在回應酬載中從要求傳回相同的字串值。

建立用戶端元件

建立另一個元件專案以實作 echo 用戶端。這個元件會連線至通訊協定實作並傳送要求。

//vendor/fuchsia-codelab 目錄中為名為 echo-client 的新元件建立專案鷹架:

mkdir -p vendor/fuchsia-codelab/echo-client

在新專案目錄中建立以下檔案和目錄結構:

Rust

//vendor/fuchsia-codelab/echo-client
                        |- BUILD.gn
                        |- meta
                        |   |- echo.cml
                        |
                        |- src
                            |- main.rs

C++

//vendor/fuchsia-codelab/echo-client
                        |- BUILD.gn
                        |- meta
                        |   |- echo.cml
                        |
                        |- main.cc

BUILD.gn 檔案中加入以下建構規則,即可建構及套件用戶端元件:

Rust

echo-client/BUILD.gn:

import("//build/components.gni")
import("//build/rust/rustc_binary.gni")


rustc_binary("bin") {
  output_name = "echo-client"
  edition = "2021"
  deps = [
    "//vendor/fuchsia-codelab/echo-fidl:echo_rust",
    "//src/lib/fuchsia",
    "//src/lib/fuchsia-component",
    "//third_party/rust_crates:anyhow",
    "//third_party/rust_crates:tracing",
  ]

  sources = [ "src/main.rs" ]
}

# Unpackaged component "#meta/echo_client.cm"
fuchsia_component("echo_client_cmp") {
  component_name = "echo_client"
  manifest = "meta/echo_client.cml"
  deps = [ ":bin" ]
}

fuchsia_package("echo-client") {
  package_name = "echo-client"
  deps = [ ":component" ]
}

C++

echo-client/BUILD.gn:

import("//build/components.gni")


executable("bin") {
  output_name = "echo-client"
  sources = [ "main.cc" ]

  deps = [
    "//vendor/fuchsia-codelab/echo-fidl:echo_hlcpp",
    "//sdk/lib/sys/cpp",
    "//sdk/lib/syslog/cpp",
    "//zircon/system/ulib/async-loop:async-loop-cpp",
    "//zircon/system/ulib/async-loop:async-loop-default",
  ]
}

# Unpackaged component "#meta/echo_client.cm"
fuchsia_component("echo_client_cmp") {
  component_name = "echo_client"
  manifest = "meta/echo_client.cml"
  deps = [ ":bin" ]
}

fuchsia_package("echo-client") {
  package_name = "echo-client"
  deps = [ ":component" ]
}

設定用戶端的元件資訊清單,以要求伺服器公開的 fidl.examples.routing.echo.Echo 能力:

Rust

echo-client/meta/echo_client.cml:

{
    include: [
        // Enable logging on stdout
        "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/echo-client",

        // Program arguments
        args: [ "Hello Fuchsia!" ],
    },


    // Capabilities used by this component.
    use: [
        { protocol: "fidl.examples.routing.echo.Echo" },
    ],
}

C++

echo-client/meta/echo_client.cml:

{
    include: [
        // Enable logging.
        "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/echo-client",

        // Program arguments
        args: [ "Hello Fuchsia!" ],
    },


    // Capabilities used by this component.
    use: [
        { protocol: "fidl.examples.routing.echo.Echo" },
    ],
}

實作用戶端

echo-args 類似,用戶端會將程式引數做為訊息傳送至伺服器。在 echo_client.cml 中新增下列程式引數:

Rust

echo-client/meta/echo_client.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/echo-client",

    // Program arguments
    args: [ "Hello Fuchsia!" ],
},

C++

echo-client/meta/echo_client.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/echo-client",

    // Program arguments
    args: [ "Hello Fuchsia!" ],
},

開啟主要來源檔案,並將匯入陳述式替換為以下程式碼:

Rust

echo-client/src/main.rs:

use fidl_fidl_examples_routing_echo::EchoMarker;
use fuchsia_component::client::connect_to_protocol;

C++

echo-client/main.cc:

#include <fidl/examples/routing/echo/cpp/fidl.h>
#include <lib/fidl/cpp/string.h>
#include <lib/sys/cpp/component_context.h>
#include <lib/syslog/cpp/log_settings.h>
#include <lib/syslog/cpp/macros.h>

#include <cstdlib>
#include <iostream>
#include <string>

將下列程式碼新增至 main(),以便連線至 Echo 通訊協定並傳送要求:

Rust

echo-client/src/main.rs:

#[fuchsia::main]
async fn main() -> Result<(), anyhow::Error> {
    // Parse arguments, removing binary name
    let mut args: Vec<String> = std::env::args().collect();
    args.remove(0);

    // Connect to FIDL protocol
    let echo = connect_to_protocol::<EchoMarker>().expect("error connecting to echo");

    // Send messages over FIDL interface
    for message in args {
        let out = echo.echo_string(Some(&message)).await.expect("echo_string failed");
        tracing::info!("Server response: {}", out.as_ref().expect("echo_string got empty result"));
    }

    Ok(())
}

EchoMarker 提供包裝函式,可依名稱連線至已公開的能力,並將控制代碼傳回至已開啟的 EchoProxy 介面。這個 Proxy 包含 echo_string() FIDL 通訊協定方法。

C++

echo-client/main.cc:

int main(int argc, const char* argv[], char* envp[]) {
  // Set tags for logging.
  fuchsia_logging::SetTags({"echo_client"});

  // Connect to FIDL protocol
  fidl::examples::routing::echo::EchoSyncPtr echo_proxy;
  auto context = sys::ComponentContext::Create();
  context->svc()->Connect(echo_proxy.NewRequest());

  // Send messages over FIDL interface for each argument
  fidl::StringPtr response = nullptr;
  for (int i = 1; i < argc; i++) {
    ZX_ASSERT(echo_proxy->EchoString(argv[i], &response) == ZX_OK);
    if (!response.has_value()) {
      FX_SLOG(INFO, "echo_string got empty result");
    } else {
      FX_SLOG(INFO, "Server response", FX_KV("response", response->c_str()));
    }
  }

  return 0;
}

EchoSyncPtr 提供包裝函式,可依名稱連線至已公開的能力,並將控制代碼傳回開啟 Proxy 介面。這個 Proxy 包含 EchoString() FIDL 通訊協定方法。

整合元件

伺服器提供的功能必須透過元件架構轉送至用戶端。如要啟用這項功能,您須實作運作領域元件做為父項,並管理能力轉送。

針對領域產品定義建立新的專案目錄:

mkdir -p vendor/fuchsia-codelab/echo-realm

在新專案目錄中建立以下檔案和目錄結構:

//vendor/fuchsia-codelab/echo-realm
                        |- BUILD.gn
                        |- meta
                        |   |- echo_realm.cml

使用下列內容建立新的元件資訊清單檔案 meta/echo_realm.cml

echo-realm/meta/echo_realm.cml:

{
    // Two children: a server and client.
    children: [
        {
            name: "echo_server",
            url: "#meta/echo_server.cm",
        },
        {
            name: "echo_client",
            url: "#meta/echo_client.cm",
        },
    ],
    offer: [
        // Route Echo protocol from server to client.
        {
            protocol: "fidl.examples.routing.echo.Echo",
            from: "#echo_server",
            to: "#echo_client",
        },

        // Route diagnostics protocols to both children.
        {
            protocol: [
                "fuchsia.inspect.InspectSink",
                "fuchsia.logger.LogSink",
            ],
            from: "parent",
            to: [
                "#echo_client",
                "#echo_server",
            ],
        },
    ],
}

這項操作會建立具有伺服器和用戶端的元件運作領域做為子項元件,並將 fidl.examples.routing.echo.Echo 通訊協定能力轉送至用戶端。

新增 BUILD.gn 檔案,為領域元件建立建構目標:

echo-realm/BUILD.gn:

import("//build/components.gni")

fuchsia_component("echo_realm") {
  manifest = "meta/echo_realm.cml"
}

fuchsia_package("echo-realm") {
  deps = [
    ":echo_realm",
    "//vendor/fuchsia-codelab/echo-server:component",
    "//vendor/fuchsia-codelab/echo-client:component",
  ]
}

更新建構設定,加入新元件:

fx set workstation_eng.x64 \
    --with //vendor/fuchsia-codelab/echo-server \
    --with //vendor/fuchsia-codelab/echo-client \
    --with //vendor/fuchsia-codelab/echo-realm

再次執行 fx build 以建構元件:

fx build

將元件新增至拓撲

您會將元件新增至 ffx-laboratory,這是在產品「核心領域」中用於開發作業的受限集合。集合可讓在執行階段動態建立及刪除元件。

如要建立元件執行個體,請將 echo-realm 元件網址和 ffx-laboratory 中的適當路徑名稱傳遞至 ffx component create

ffx component create /core/ffx-laboratory:echo-realm \
    fuchsia-pkg://fuchsia.com/echo-realm#meta/echo_realm.cm

然後,使用 ffx component resolve 解析 echo-realm 元件:

ffx component resolve /core/ffx-laboratory:echo-realm

使用 ffx component show 驗證伺服器和用戶端的執行個體是否已建立為子項元件:

ffx component show echo
               Moniker: /core/ffx-laboratory:echo-realm/echo_client
                   URL: #meta/echo_client.cm
                  Type: CML static component
       Component State: Unresolved
       Execution State: Stopped

               Moniker: /core/ffx-laboratory:echo-realm/echo_server
                   URL: #meta/echo_server.cm
                  Type: CML static component
       Component State: Unresolved
       Execution State: Stopped

               Moniker: /core/ffx-laboratory:echo-realm
                   URL: fuchsia-pkg://fuchsia.com/echo-realm#meta/echo_realm.cm
                  Type: CML dynamic component
       Component State: Resolved
       Execution State: Stopped
           Merkle root: 666c40477785f89b0ace22b30d65f1338f1d308ecceacb0f65f5140baa889e1b

驗證元件互動

使用 ffx component start 啟動現有的用戶端元件執行個體:

ffx component start /core/ffx-laboratory:echo-realm/echo_client

開啟另一個終端機視窗,並驗證用戶端元件的輸出記錄:

ffx log --filter echo

裝置記錄中應會顯示下列輸出內容:

[echo_client][I] Server response: Hello, Fuchsia!

伺服器元件會在用戶端與 fidl.examples.routing.echo.Echo 能力連線後啟動,並繼續提供其他 FIDL 要求。

請使用 ffx component show 查看在元件執行個體樹狀結構中執行的 echo 伺服器:

ffx component show echo_server
               Moniker: /core/ffx-laboratory:echo-realm/echo_server
                   URL: #meta/echo_server.cm
                  Type: CML static component
       Component State: Resolved
 Incoming Capabilities: fuchsia.logger.LogSink
  Exposed Capabilities: diagnostics
                        fidl.examples.routing.echo.Echo
       Execution State: Running
                Job ID: 474691
            Process ID: 474712
           Running for: 2026280474361 ticks
           Merkle root: 666c40477785f89b0ace22b30d65f1338f1d308ecceacb0f65f5140baa889e1b
 Outgoing Capabilities: diagnostics
                        fidl.examples.routing.echo.Echo

刪除執行個體

使用下列指令清除 echo-realm 例項:

ffx component destroy /core/ffx-laboratory:echo-realm